Java Examples for org.eclipse.aether.artifact.DefaultArtifact
The following java examples will help you to understand the usage of org.eclipse.aether.artifact.DefaultArtifact. These source code samples are taken from different open source projects.
Example 1
| Project: aether-ant-master File: AntRepoSys.java View source code |
private List<org.eclipse.aether.artifact.Artifact> toArtifacts(Task task, RepositorySystemSession session, Pom pom, Artifacts artifacts) {
Model model = pom.getModel(task);
File pomFile = pom.getFile();
List<org.eclipse.aether.artifact.Artifact> results = new ArrayList<org.eclipse.aether.artifact.Artifact>();
org.eclipse.aether.artifact.Artifact pomArtifact = new DefaultArtifact(model.getGroupId(), model.getArtifactId(), "pom", model.getVersion()).setFile(pomFile);
results.add(pomArtifact);
for (Artifact artifact : artifacts.getArtifacts()) {
org.eclipse.aether.artifact.Artifact buildArtifact = new DefaultArtifact(model.getGroupId(), model.getArtifactId(), artifact.getClassifier(), artifact.getType(), model.getVersion()).setFile(artifact.getFile());
results.add(buildArtifact);
}
return results;
}Example 2
| Project: frontend-maven-plugin-master File: RepositoryCacheResolver.java View source code |
private DefaultArtifact createArtifact(CacheDescriptor cacheDescriptor) { String version = cacheDescriptor.getVersion().replaceAll("^v", ""); DefaultArtifact artifact; if (cacheDescriptor.getClassifier() == null) { artifact = new DefaultArtifact(GROUP_ID, cacheDescriptor.getName(), cacheDescriptor.getExtension(), version); } else { artifact = new DefaultArtifact(GROUP_ID, cacheDescriptor.getName(), cacheDescriptor.getClassifier(), cacheDescriptor.getExtension(), version); } return artifact; }
Example 3
| Project: maven-install-plugin-master File: RepositoryCacheResolver.java View source code |
private DefaultArtifact createArtifact(CacheDescriptor cacheDescriptor) { String version = cacheDescriptor.getVersion().replaceAll("^v", ""); DefaultArtifact artifact; if (cacheDescriptor.getClassifier() == null) { artifact = new DefaultArtifact(GROUP_ID, cacheDescriptor.getName(), cacheDescriptor.getExtension(), version); } else { artifact = new DefaultArtifact(GROUP_ID, cacheDescriptor.getName(), cacheDescriptor.getClassifier(), cacheDescriptor.getExtension(), version); } return artifact; }
Example 4
| Project: karaf-master File: GenerateDescriptorMojo.java View source code |
private void processFeatureArtifact(Features features, Feature feature, Map<Dependency, Feature> otherFeatures, Map<Feature, String> featureRepositories, Object artifact, Object parent, boolean add) throws MojoExecutionException, XMLStreamException, JAXBException, IOException {
if (this.dependencyHelper.isArtifactAFeature(artifact) && FEATURE_CLASSIFIER.equals(this.dependencyHelper.getClassifier(artifact))) {
File featuresFile = this.dependencyHelper.resolve(artifact, getLog());
if (featuresFile == null || !featuresFile.exists()) {
throw new MojoExecutionException("Cannot locate file for feature: " + artifact + " at " + featuresFile);
}
Features includedFeatures = readFeaturesFile(featuresFile);
for (String repository : includedFeatures.getRepository()) {
processFeatureArtifact(features, feature, otherFeatures, featureRepositories, new DefaultArtifact(MavenUtil.mvnToAether(repository)), parent, false);
}
for (Feature includedFeature : includedFeatures.getFeature()) {
Dependency dependency = new Dependency(includedFeature.getName(), includedFeature.getVersion());
dependency.setPrerequisite(prerequisiteFeatures.contains(dependency.getName()));
dependency.setDependency(dependencyFeatures.contains(dependency.getName()));
// Determine what dependency we're actually going to use
Dependency matchingDependency = findMatchingDependency(feature.getFeature(), dependency);
if (matchingDependency != null) {
// The feature already has a matching dependency, merge
mergeDependencies(matchingDependency, dependency);
dependency = matchingDependency;
}
// We mustn't de-duplicate here, we may have seen a feature in !add mode
otherFeatures.put(dependency, includedFeature);
if (add) {
if (!feature.getFeature().contains(dependency)) {
feature.getFeature().add(dependency);
}
if (aggregateFeatures) {
features.getFeature().add(includedFeature);
}
}
if (!featureRepositories.containsKey(includedFeature)) {
featureRepositories.put(includedFeature, this.dependencyHelper.artifactToMvn(artifact, getVersionOrRange(parent, artifact)));
}
}
}
}Example 5
| Project: aether-core-master File: DefaultUpdateCheckManagerTest.java View source code |
@Before
public void setup() throws Exception {
File dir = TestFileUtils.createTempFile("");
TestFileUtils.deleteFile(dir);
File metadataFile = new File(dir, "metadata.txt");
TestFileUtils.writeString(metadataFile, "metadata");
File artifactFile = new File(dir, "artifact.txt");
TestFileUtils.writeString(artifactFile, "artifact");
session = TestUtils.newSession();
repository = new RemoteRepository.Builder("id", "default", TestFileUtils.createTempDir().toURI().toURL().toString()).build();
manager = new DefaultUpdateCheckManager().setUpdatePolicyAnalyzer(new DefaultUpdatePolicyAnalyzer());
metadata = new DefaultMetadata("gid", "aid", "ver", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT, metadataFile);
artifact = new DefaultArtifact("gid", "aid", "", "ext", "ver").setFile(artifactFile);
}Example 6
| Project: aether-demo-master File: Aether.java View source code |
public AetherResult resolve(String groupId, String artifactId, String version) throws DependencyResolutionException {
RepositorySystemSession session = newSession();
Dependency dependency = new Dependency(new DefaultArtifact(groupId, artifactId, "", "jar", version), "runtime");
RemoteRepository central = new RemoteRepository.Builder("central", "default", remoteRepository).build();
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot(dependency);
collectRequest.addRepository(central);
DependencyRequest dependencyRequest = new DependencyRequest();
dependencyRequest.setCollectRequest(collectRequest);
DependencyNode rootNode = repositorySystem.resolveDependencies(session, dependencyRequest).getRoot();
StringBuilder dump = new StringBuilder();
displayTree(rootNode, dump);
PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
rootNode.accept(nlg);
return new AetherResult(rootNode, nlg.getFiles(), nlg.getClassPath());
}Example 7
| Project: recommenders-master File: ModelIndex.java View source code |
@Override
public ImmutableSet<ModelCoordinate> suggestCandidates(ProjectCoordinate pc, String modelType) {
Checks.ensureIsNotNull(modelType);
if (!isAccessible()) {
return ImmutableSet.of();
}
readLock.lock();
try {
Builder<ModelCoordinate> res = ImmutableSet.builder();
for (String model : queryLuceneIndexForModelCandidates(pc, modelType)) {
Artifact tmp = new DefaultArtifact(model);
ModelCoordinate mc = toModelCoordinate(tmp);
res.add(mc);
}
return res.build();
} finally {
readLock.unlock();
}
}Example 8
| Project: xmvn-master File: XMvnPluginVersionResolver.java View source code |
@Override
public PluginVersionResult resolve(PluginVersionRequest request) {
RepositorySystemSession session = request.getRepositorySession();
WorkspaceReader reader = session.getWorkspaceReader();
List<String> versions = reader.findVersions(new DefaultArtifact(request.getGroupId(), request.getArtifactId(), Artifact.DEFAULT_EXTENSION, Artifact.DEFAULT_VERSION));
final String version = versions.isEmpty() ? Artifact.DEFAULT_VERSION : versions.iterator().next();
final ArtifactRepository repository = reader.getRepository();
return new PluginVersionResult() {
@Override
public ArtifactRepository getRepository() {
return repository;
}
@Override
public String getVersion() {
return version;
}
};
}Example 9
| Project: bnd-master File: AetherRepository.java View source code |
@Override
public SortedSet<Version> versions(String bsn) throws Exception {
init();
// Use the index by preference
if (indexedRepo != null)
return indexedRepo.versions(ConversionUtils.maybeMavenCoordsToBsn(bsn));
Artifact artifact = null;
try {
artifact = new DefaultArtifact(bsn + ":[0,)");
} catch (Exception e) {
}
if (artifact == null)
return null;
// Setup the Aether repo session and create the range request
DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
session.setLocalRepositoryManager(repoSystem.newLocalRepositoryManager(session, localRepo));
VersionRangeRequest rangeRequest = new VersionRangeRequest();
rangeRequest.setArtifact(artifact);
rangeRequest.setRepositories(Collections.singletonList(remoteRepo));
// Resolve the range
VersionRangeResult rangeResult = repoSystem.resolveVersionRange(session, rangeRequest);
// Add to the result
SortedSet<Version> versions = new TreeSet<Version>();
for (org.eclipse.aether.version.Version version : rangeResult.getVersions()) {
try {
versions.add(MavenVersion.parseString(version.toString()).getOSGiVersion());
} catch (IllegalArgumentException e) {
}
}
return versions;
}Example 10
| Project: elasticsearch-maven-plugin-master File: MyArtifactResolver.java View source code |
/**
* Resolves an Artifact from the repositories.
*
* @param coordinates The artifact coordinates
* @return The local file resolved/downloaded for the given coordinates
* @throws ResolutionException If the artifact cannot be resolved
*/
public File resolveArtifact(String coordinates) throws ResolutionException {
ArtifactRequest request = new ArtifactRequest();
Artifact artifact = new DefaultArtifact(coordinates);
request.setArtifact(artifact);
request.setRepositories(remoteRepositories);
log.debug(String.format("Resolving artifact %s from %s", artifact, remoteRepositories));
ArtifactResult result;
try {
result = repositorySystem.resolveArtifact(repositorySession, request);
} catch (ArtifactResolutionException e) {
throw new ResolutionException(e.getMessage(), e);
}
log.debug(String.format("Resolved artifact %s to %s from %s", artifact, result.getArtifact().getFile(), result.getRepository()));
return result.getArtifact().getFile();
}Example 11
| Project: gshell-master File: ResolveDependenciesAction.java View source code |
@Override
public Object execute(@Nonnull final CommandContext context) throws Exception {
DefaultRepositorySystemSession session = repositoryAccess.createSession();
session.setTransferListener(new IOTransferListener(context.getIo()));
Artifact artifact = new DefaultArtifact(coordinates);
Dependency dependency = new Dependency(artifact, scope);
CollectRequest collectRequest = new CollectRequest(dependency, repositoryAccess.getRemoteRepositories());
DependencyRequest request = new DependencyRequest(collectRequest, null);
log.debug("Resolving dependencies: {}", dependency);
DependencyResult result = repositoryAccess.getRepositorySystem().resolveDependencies(session, request);
new DependencyNodePrinter(context.getIo()).print(result.getRoot());
return null;
}Example 12
| Project: Mav-master File: RepositoryUtils.java View source code |
public static org.apache.maven.artifact.Artifact toArtifact(Artifact artifact) {
if (artifact == null) {
return null;
}
ArtifactHandler handler = newHandler(artifact);
/*
* NOTE: From Artifact.hasClassifier(), an empty string and a null both denote "no classifier". However, some
* plugins only check for null, so be sure to nullify an empty classifier.
*/
org.apache.maven.artifact.Artifact result = new org.apache.maven.artifact.DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), null, artifact.getProperty(ArtifactProperties.TYPE, artifact.getExtension()), nullify(artifact.getClassifier()), handler);
result.setFile(artifact.getFile());
result.setResolved(artifact.getFile() != null);
List<String> trail = new ArrayList<>(1);
trail.add(result.getId());
result.setDependencyTrail(trail);
return result;
}Example 13
| Project: maven-master File: RepositoryUtils.java View source code |
public static org.apache.maven.artifact.Artifact toArtifact(Artifact artifact) {
if (artifact == null) {
return null;
}
ArtifactHandler handler = newHandler(artifact);
/*
* NOTE: From Artifact.hasClassifier(), an empty string and a null both denote "no classifier". However, some
* plugins only check for null, so be sure to nullify an empty classifier.
*/
org.apache.maven.artifact.Artifact result = new org.apache.maven.artifact.DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), null, artifact.getProperty(ArtifactProperties.TYPE, artifact.getExtension()), nullify(artifact.getClassifier()), handler);
result.setFile(artifact.getFile());
result.setResolved(artifact.getFile() != null);
List<String> trail = new ArrayList<>(1);
trail.add(result.getId());
result.setDependencyTrail(trail);
return result;
}Example 14
| Project: MULE-master File: AetherClassPathClassifier.java View source code |
/**
* Discovers the {@link Dependency} from the list of directDependencies using the artifact coordiantes in format of:
*
* <pre>
* groupId:artifactId
* </pre>
* <p/>
* If the coordinates matches to the rootArtifact it will return a {@value org.eclipse.aether.util.artifact.JavaScopes#COMPILE}
* {@link Dependency}.
*
* @param artifactCoords Maven coordinates that define the artifact dependency
* @param rootArtifact {@link Artifact} that defines the current artifact that requested to build this class loaders
* @param directDependencies {@link List} of {@link Dependency} with direct dependencies for the rootArtifact
* @return {@link Dependency} representing the artifact if declared as direct dependency or rootArtifact if they match it or
* {@link Optional#EMPTY} if couldn't found the dependency.
* @throws {@link IllegalArgumentException} if artifactCoords are not in the expected format
*/
public Optional<Dependency> discoverDependency(String artifactCoords, Artifact rootArtifact, List<Dependency> directDependencies) {
final String[] artifactCoordsSplit = artifactCoords.split(MAVEN_COORDINATES_SEPARATOR);
if (artifactCoordsSplit.length != 2) {
throw new IllegalArgumentException("Artifact coordinates should be in format of groupId:artifactId, '" + artifactCoords + "' is not a valid format");
}
String groupId = artifactCoordsSplit[0];
String artifactId = artifactCoordsSplit[1];
if (rootArtifact.getGroupId().equals(groupId) && rootArtifact.getArtifactId().equals(artifactId)) {
logger.debug("'{}' artifact coordinates matched with rootArtifact '{}', resolving version from rootArtifact", artifactCoords, rootArtifact);
final DefaultArtifact artifact = new DefaultArtifact(groupId, artifactId, JAR_EXTENSION, rootArtifact.getVersion());
logger.debug("'{}' artifact coordinates resolved to: '{}'", artifactCoords, artifact);
return Optional.of(new Dependency(artifact, COMPILE));
} else {
logger.debug("Resolving version for '{}' from direct dependencies", artifactCoords);
return findDirectDependency(groupId, artifactId, directDependencies);
}
}Example 15
| Project: package-drone-master File: AetherImporter.java View source code |
/**
* Prepare an import with dependencies
* <p>
* This method does resolve even transient dependencies and also adds the
* sources if requested
* </p>
*/
public static AetherResult prepareDependencies(final Path tmpDir, final ImportConfiguration cfg) throws RepositoryException {
Objects.requireNonNull(tmpDir);
Objects.requireNonNull(cfg);
final RepositoryContext ctx = new RepositoryContext(tmpDir, cfg.getRepositoryUrl(), cfg.isAllOptional());
// add all coordinates
final CollectRequest cr = new CollectRequest();
cr.setRepositories(ctx.getRepositories());
for (final MavenCoordinates coords : cfg.getCoordinates()) {
final Dependency dep = new Dependency(new DefaultArtifact(coords.toString()), COMPILE);
cr.addDependency(dep);
}
final DependencyFilter filter = DependencyFilterUtils.classpathFilter(COMPILE);
final DependencyRequest deps = new DependencyRequest(cr, filter);
// resolve
final DependencyResult dr = ctx.getSystem().resolveDependencies(ctx.getSession(), deps);
final List<ArtifactResult> arts = dr.getArtifactResults();
if (!cfg.isIncludeSources()) {
// we are already done here
return asResult(arts, cfg, of(dr));
}
// resolve sources
final List<ArtifactRequest> requests = extendRequests(arts.stream().map(ArtifactResult::getRequest), ctx, cfg);
return asResult(resolve(ctx, requests), cfg, of(dr));
}Example 16
| Project: wildfly-maven-plugin-master File: EclipseAetherArtifactResolver.java View source code |
@Override
public File resolve(final MavenProject project, final String artifact) {
final ArtifactResult result;
try {
final ProjectBuildingRequest projectBuildingRequest = project.getProjectBuildingRequest();
final ArtifactRequest request = new ArtifactRequest();
final ArtifactNameSplitter splitter = ArtifactNameSplitter.of(artifact).split();
final Artifact defaultArtifact = new DefaultArtifact(splitter.getGroupId(), splitter.getArtifactId(), splitter.getClassifier(), splitter.getPackaging(), splitter.getVersion());
request.setArtifact(defaultArtifact);
final List<RemoteRepository> repos = project.getRemoteProjectRepositories();
request.setRepositories(repos);
result = repoSystem.resolveArtifact(projectBuildingRequest.getRepositorySession(), request);
} catch (ArtifactResolutionException e) {
throw new RuntimeException(e.getMessage(), e);
}
return result.getArtifact().getFile();
}Example 17
| Project: xwiki-commons-master File: AetherExtensionRepository.java View source code |
private AetherExtension resolveMaven(Artifact artifact, String artifactExtension, RepositorySystemSession session) throws ResolveException {
// Get Maven descriptor
Model model;
try {
model = loadPom(artifact, session);
} catch (ArtifactResolutionException e1) {
if (e1.getResult() != null && !e1.getResult().getExceptions().isEmpty() && e1.getResult().getExceptions().get(0) instanceof ArtifactNotFoundException) {
throw new ExtensionNotFoundException("Could not find artifact [" + artifact + "] descriptor", e1);
} else {
throw new ResolveException("Failed to resolve artifact [" + artifact + "] descriptor", e1);
}
} catch (Exception e2) {
throw new ResolveException("Failed to resolve artifact [" + artifact + "] descriptor", e2);
}
if (model == null) {
throw new ResolveException("Failed to resolve artifact [" + artifact + "] descriptor");
}
if (artifactExtension == null) {
// Resolve extension from the pom packaging
ArtifactType artifactType = session.getArtifactTypeRegistry().get(model.getPackaging());
if (artifactType != null) {
artifactExtension = artifactType.getExtension();
} else {
artifactExtension = model.getPackaging();
}
}
Extension mavenExtension = this.extensionConverter.convert(Extension.class, model);
Artifact filerArtifact = new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(), artifactExtension, artifact.getVersion());
AetherExtension extension = new AetherExtension(mavenExtension, filerArtifact, this, factory);
// Convert Maven dependencies to Aether dependencies
extension.setDependencies(toAetherDependencies(mavenExtension.getDependencies(), session));
// Convert Managed Maven dependencies to Aether dependencies
extension.setManagedDependencies(toAetherDependencies(mavenExtension.getManagedDependencies(), session));
return extension;
}Example 18
| Project: bazel-master File: MavenDownloader.java View source code |
/**
* Download the Maven artifact to the output directory. Returns the path to the jar.
*/
public Path download(String name, WorkspaceAttributeMapper mapper, Path outputDirectory, MavenServerValue serverValue) throws IOException, EvalException {
this.name = name;
this.outputDirectory = outputDirectory;
String url = serverValue.getUrl();
Server server = serverValue.getServer();
Artifact artifact;
String artifactId = mapper.get("artifact", Type.STRING);
String sha1 = mapper.isAttributeValueExplicitlySpecified("sha1") ? mapper.get("sha1", Type.STRING) : null;
if (sha1 != null && !KeyType.SHA1.isValid(sha1)) {
throw new IOException("Invalid SHA-1 for maven_jar " + name + ": '" + sha1 + "'");
}
try {
artifact = new DefaultArtifact(artifactId);
} catch (IllegalArgumentException e) {
throw new IOException(e.getMessage());
}
boolean isCaching = repositoryCache.isEnabled() && KeyType.SHA1.isValid(sha1);
if (isCaching) {
Path downloadPath = getDownloadDestination(artifact);
Path cachedDestination = repositoryCache.get(sha1, downloadPath, KeyType.SHA1);
if (cachedDestination != null) {
return cachedDestination;
}
}
MavenConnector connector = new MavenConnector(outputDirectory.getPathString());
RepositorySystem system = connector.newRepositorySystem();
RepositorySystemSession session = connector.newRepositorySystemSession(system);
RemoteRepository repository = new RemoteRepository.Builder(name, MavenServerValue.DEFAULT_ID, url).setAuthentication(new MavenAuthentication(server)).build();
ArtifactRequest artifactRequest = new ArtifactRequest();
artifactRequest.setArtifact(artifact);
artifactRequest.setRepositories(ImmutableList.of(repository));
try {
ArtifactResult artifactResult = system.resolveArtifact(session, artifactRequest);
artifact = artifactResult.getArtifact();
} catch (ArtifactResolutionException e) {
throw new IOException("Failed to fetch Maven dependency: " + e.getMessage());
}
Path downloadPath = outputDirectory.getRelative(artifact.getFile().getAbsolutePath());
// Verify checksum.
if (!Strings.isNullOrEmpty(sha1)) {
RepositoryCache.assertFileChecksum(sha1, downloadPath, KeyType.SHA1);
}
if (isCaching) {
repositoryCache.put(sha1, downloadPath, KeyType.SHA1);
}
return downloadPath;
}Example 19
| Project: build-monitor-master File: ArtifactTransporter.java View source code |
public Path get(@NotNull String groupName, @NotNull String artifactName, @NotNull String version, @NotNull String artifactFileExtension) {
Artifact artifact = new DefaultArtifact(groupName, artifactName, artifactFileExtension, version);
RepositorySystem system = newRepositorySystem();
RepositorySystemSession session = newRepositorySystemSession(system);
ArtifactRequest request = new ArtifactRequest();
request.setArtifact(artifact);
request.setRepositories(repositories(system, session));
try {
ArtifactResult artifactResult = system.resolveArtifact(session, request);
artifact = artifactResult.getArtifact();
Log.info(artifact + " resolved to " + artifact.getFile());
return artifact.getFile().toPath();
} catch (ArtifactResolutionException e) {
throw new RuntimeException(format("Couldn't resolve a '%s' artifact for '%s:%s:%s'", artifactFileExtension, groupName, artifactName, version), e);
}
}Example 20
| Project: byte-buddy-master File: ClassLoaderResolverTest.java View source code |
@Before
public void setUp() throws Exception {
classLoaderResolver = new ClassLoaderResolver(log, repositorySystem, repositorySystemSession, Collections.<RemoteRepository>emptyList());
when(repositorySystem.collectDependencies(eq(repositorySystemSession), any(CollectRequest.class))).thenReturn(new CollectResult(new CollectRequest()).setRoot(root));
when(child.getDependency()).thenReturn(new Dependency(new DefaultArtifact(FOO, BAR, QUX, BAZ, FOO + BAR, Collections.<String, String>emptyMap(), new File(FOO + "/" + BAR)), QUX + BAZ));
when(root.accept(any(DependencyVisitor.class))).then(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
DependencyVisitor dependencyVisitor = invocationOnMock.getArgument(0);
dependencyVisitor.visitEnter(child);
dependencyVisitor.visitLeave(child);
return null;
}
});
}Example 21
| Project: Correct-master File: MavenDownloader.java View source code |
/**
* Download the Maven artifact to the output directory. Returns the path to the jar.
*/
public Path download(String name, WorkspaceAttributeMapper mapper, Path outputDirectory, MavenServerValue serverValue) throws IOException, EvalException {
this.name = name;
this.outputDirectory = outputDirectory;
String url = serverValue.getUrl();
Server server = serverValue.getServer();
Artifact artifact;
String artifactId = mapper.get("artifact", Type.STRING);
String sha1 = mapper.isAttributeValueExplicitlySpecified("sha1") ? mapper.get("sha1", Type.STRING) : null;
if (sha1 != null && !KeyType.SHA1.isValid(sha1)) {
throw new IOException("Invalid SHA-1 for maven_jar " + name + ": '" + sha1 + "'");
}
try {
artifact = new DefaultArtifact(artifactId);
} catch (IllegalArgumentException e) {
throw new IOException(e.getMessage());
}
boolean isCaching = repositoryCache.isEnabled() && KeyType.SHA1.isValid(sha1);
if (isCaching) {
Path downloadPath = getDownloadDestination(artifact);
Path cachedDestination = repositoryCache.get(sha1, downloadPath, KeyType.SHA1);
if (cachedDestination != null) {
return cachedDestination;
}
}
MavenConnector connector = new MavenConnector(outputDirectory.getPathString());
RepositorySystem system = connector.newRepositorySystem();
RepositorySystemSession session = connector.newRepositorySystemSession(system);
RemoteRepository repository = new RemoteRepository.Builder(name, MavenServerValue.DEFAULT_ID, url).setAuthentication(new MavenAuthentication(server)).build();
ArtifactRequest artifactRequest = new ArtifactRequest();
artifactRequest.setArtifact(artifact);
artifactRequest.setRepositories(ImmutableList.of(repository));
try {
ArtifactResult artifactResult = system.resolveArtifact(session, artifactRequest);
artifact = artifactResult.getArtifact();
} catch (ArtifactResolutionException e) {
throw new IOException("Failed to fetch Maven dependency: " + e.getMessage());
}
Path downloadPath = outputDirectory.getRelative(artifact.getFile().getAbsolutePath());
// Verify checksum.
if (!Strings.isNullOrEmpty(sha1)) {
RepositoryCache.assertFileChecksum(sha1, downloadPath, KeyType.SHA1);
}
if (isCaching) {
repositoryCache.put(sha1, downloadPath, KeyType.SHA1);
}
return downloadPath;
}Example 22
| Project: java-virtual-machine-master File: ClassLoaderResolverTest.java View source code |
@Before
public void setUp() throws Exception {
classLoaderResolver = new ClassLoaderResolver(log, repositorySystem, repositorySystemSession, Collections.<RemoteRepository>emptyList());
when(repositorySystem.collectDependencies(eq(repositorySystemSession), any(CollectRequest.class))).thenReturn(new CollectResult(new CollectRequest()).setRoot(root));
when(child.getDependency()).thenReturn(new Dependency(new DefaultArtifact(FOO, BAR, QUX, BAZ, FOO + BAR, Collections.<String, String>emptyMap(), new File(FOO + "/" + BAR)), QUX + BAZ));
when(root.accept(any(DependencyVisitor.class))).then(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
DependencyVisitor dependencyVisitor = invocationOnMock.getArgument(0);
dependencyVisitor.visitEnter(child);
dependencyVisitor.visitLeave(child);
return null;
}
});
}Example 23
| Project: jboss-as-maven-plugin-master File: EclipseAetherArtifactResolver.java View source code |
@Override
public File resolve(final MavenProject project, final String artifact) {
final ArtifactResult result;
try {
ProjectBuildingRequest projectBuildingRequest = invoke(project, "getProjectBuildingRequest", ProjectBuildingRequest.class);
final ArtifactRequest request = new ArtifactRequest();
final DefaultArtifact defaultArtifact = createArtifact(artifact);
request.setArtifact(defaultArtifact);
@SuppressWarnings("unchecked") final List<RemoteRepository> repos = invoke(project, "getRemoteProjectRepositories", List.class);
request.setRepositories(repos);
result = repoSystem.resolveArtifact(invoke(projectBuildingRequest, "getRepositorySession", RepositorySystemSession.class), request);
} catch (ArtifactResolutionException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getMessage(), e);
}
return result.getArtifact().getFile();
}Example 24
| Project: jenkins-build-monitor-plugin-master File: ArtifactTransporter.java View source code |
public Path get(@NotNull String groupName, @NotNull String artifactName, @NotNull String version, @NotNull String artifactFileExtension) {
Artifact artifact = new DefaultArtifact(groupName, artifactName, artifactFileExtension, version);
RepositorySystem system = newRepositorySystem();
RepositorySystemSession session = newRepositorySystemSession(system);
ArtifactRequest request = new ArtifactRequest();
request.setArtifact(artifact);
request.setRepositories(repositories(system, session));
try {
ArtifactResult artifactResult = system.resolveArtifact(session, request);
artifact = artifactResult.getArtifact();
Log.info(artifact + " resolved to " + artifact.getFile());
return artifact.getFile().toPath();
} catch (ArtifactResolutionException e) {
throw new RuntimeException(format("Couldn't resolve a '%s' artifact for '%s:%s:%s'", artifactFileExtension, groupName, artifactName, version), e);
}
}Example 25
| Project: maven-debian-helper-master File: PlexusUtilsInjector.java View source code |
public DependencyNode transformGraph(DependencyNode node, DependencyGraphTransformationContext context) throws RepositoryException {
if (findPlexusUtils(node) == null) {
Artifact pu = new DefaultArtifact(GID, AID, null, EXT, VER);
DefaultDependencyNode child = new DefaultDependencyNode(new Dependency(pu, JavaScopes.RUNTIME));
child.setRepositories(node.getRepositories());
child.setRequestContext(node.getRequestContext());
node.getChildren().add(child);
}
return node;
}Example 26
| Project: Rio-master File: AetherService.java View source code |
/**
* Resolve an artifact with the specified coordinates.
*
* @param groupId The group identifier of the artifact, may be {@code null}.
* @param artifactId The artifact identifier of the artifact, may be {@code null}.
* @param extension The file extension of the artifact, may be {@code null}.
* @param classifier The classifier of the artifact, may be {@code null}.
* @param version The version of the artifact, may be {@code null}.
* @param repositories A collection of repositories to use when resolving the artifact,
* may be {@code null}. If {@code null}, the repositories will be determined by reading the settings
*
* @return A <code>ResolutionResult</code> for the artifact with the specified coordinates.
*
* @throws DependencyCollectionException If errors are encountered creating the collection of dependencies
* @throws DependencyResolutionException If errors are encountered resolving dependencies
* @throws SettingsBuildingException If errors are encountered handling settings
*/
public ResolutionResult resolve(final String groupId, final String artifactId, final String extension, final String classifier, final String version, final List<RemoteRepository> repositories) throws DependencyCollectionException, DependencyResolutionException, SettingsBuildingException, VersionRangeResolutionException {
RepositorySystemSession session = newSession(repositorySystem, workspaceReader, SettingsUtil.getLocalRepositoryLocation(effectiveSettings));
List<RemoteRepository> myRepositories;
if (repositories == null || repositories.isEmpty())
myRepositories = getRemoteRepositories();
else
myRepositories = repositories;
setMirrorSelector(myRepositories, (DefaultRepositorySystemSession) session);
List<RemoteRepository> repositoriesToUse = applyAuthentication(myRepositories);
String actualVersion = version;
if (version.endsWith("LATEST")) {
DefaultArtifact artifact = new DefaultArtifact(groupId, artifactId, classifier, extension, "[0,)");
actualVersion = getLatestVersion(artifact, session, repositoriesToUse);
}
DefaultArtifact artifact = new DefaultArtifact(groupId, artifactId, classifier, extension, actualVersion);
Dependency dependency = new Dependency(artifact, /*JavaScopes.RUNTIME*/
dependencyFilterScope == null ? JavaScopes.RUNTIME : dependencyFilterScope);
if (logger.isDebugEnabled()) {
StringBuilder builder = new StringBuilder();
for (RemoteRepository r : repositoriesToUse) {
if (builder.length() > 0)
builder.append(", ");
builder.append(r.getUrl());
}
logger.debug("Resolve {} using repositories {}", artifact, builder.toString());
}
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot(dependency);
collectRequest.setRepositories(repositoriesToUse);
DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, getDependencyFilter(artifact));
dependencyRequest.setCollectRequest(collectRequest);
try {
List<ArtifactResult> artifactResults = repositorySystem.resolveDependencies(session, dependencyRequest).getArtifactResults();
return new ResolutionResult(artifact, artifactResults);
} catch (NullPointerException e) {
String message = String.format("Trying to resolve %s, failed to read artifact descriptor, " + "make sure that all parent poms are resolve-able", artifact);
throw new DependencyCollectionException(new CollectResult(collectRequest), message, e);
}
}Example 27
| Project: smartics-jboss-modules-maven-plugin-master File: Mapper.java View source code |
private Artifact extractArtifact(final org.apache.maven.model.Dependency mavenDependency) {
final String groupId = mavenDependency.getGroupId();
final String artifactId = mavenDependency.getArtifactId();
final String classifier = mavenDependency.getClassifier();
final String extension = mavenDependency.getType();
final String version = mavenDependency.getVersion();
final Artifact aetherArtifact = new DefaultArtifact(groupId, artifactId, classifier, extension, version);
return aetherArtifact;
}Example 28
| Project: spring-boot-master File: AetherGrapeEngine.java View source code |
private Artifact createArtifact(Map<?, ?> dependencyMap) {
String group = (String) dependencyMap.get("group");
String module = (String) dependencyMap.get("module");
String version = (String) dependencyMap.get("version");
if (version == null) {
version = this.resolutionContext.getManagedVersion(group, module);
}
String classifier = (String) dependencyMap.get("classifier");
String type = determineType(dependencyMap);
return new DefaultArtifact(group, module, classifier, type, version);
}Example 29
| Project: takari-local-repository-master File: TakariUpdateCheckManagerTest.java View source code |
@Before
public void setup() throws Exception {
File dir = TestFileUtils.createTempFile("");
TestFileUtils.delete(dir);
File metadataFile = new File(dir, "metadata.txt");
TestFileUtils.write("metadata", metadataFile);
File artifactFile = new File(dir, "artifact.txt");
TestFileUtils.write("artifact", artifactFile);
session = TestUtils.newSession();
repository = new RemoteRepository.Builder("id", "default", TestFileUtils.createTempDir().toURI().toURL().toString()).build();
manager = new TakariUpdateCheckManager().setUpdatePolicyAnalyzer(new DefaultUpdatePolicyAnalyzer());
metadata = new DefaultMetadata("gid", "aid", "ver", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT, metadataFile);
artifact = new DefaultArtifact("gid", "aid", "", "ext", "ver").setFile(artifactFile);
}Example 30
| Project: test-master File: MavenDownloader.java View source code |
/**
* Download the Maven artifact to the output directory. Returns the path to the jar.
*/
public Path download(String name, WorkspaceAttributeMapper mapper, Path outputDirectory, MavenServerValue serverValue) throws IOException, EvalException {
this.name = name;
this.outputDirectory = outputDirectory;
String url = serverValue.getUrl();
Server server = serverValue.getServer();
Artifact artifact;
String artifactId = mapper.get("artifact", Type.STRING);
String sha1 = mapper.isAttributeValueExplicitlySpecified("sha1") ? mapper.get("sha1", Type.STRING) : null;
if (sha1 != null && !KeyType.SHA1.isValid(sha1)) {
throw new IOException("Invalid SHA-1 for maven_jar " + name + ": '" + sha1 + "'");
}
try {
artifact = new DefaultArtifact(artifactId);
} catch (IllegalArgumentException e) {
throw new IOException(e.getMessage());
}
boolean isCaching = repositoryCache.isEnabled() && KeyType.SHA1.isValid(sha1);
if (isCaching) {
Path downloadPath = getDownloadDestination(artifact);
Path cachedDestination = repositoryCache.get(sha1, downloadPath, KeyType.SHA1);
if (cachedDestination != null) {
return cachedDestination;
}
}
MavenConnector connector = new MavenConnector(outputDirectory.getPathString());
RepositorySystem system = connector.newRepositorySystem();
RepositorySystemSession session = connector.newRepositorySystemSession(system);
RemoteRepository repository = new RemoteRepository.Builder(name, MavenServerValue.DEFAULT_ID, url).setAuthentication(new MavenAuthentication(server)).build();
ArtifactRequest artifactRequest = new ArtifactRequest();
artifactRequest.setArtifact(artifact);
artifactRequest.setRepositories(ImmutableList.of(repository));
try {
ArtifactResult artifactResult = system.resolveArtifact(session, artifactRequest);
artifact = artifactResult.getArtifact();
} catch (ArtifactResolutionException e) {
throw new IOException("Failed to fetch Maven dependency: " + e.getMessage());
}
Path downloadPath = outputDirectory.getRelative(artifact.getFile().getAbsolutePath());
// Verify checksum.
if (!Strings.isNullOrEmpty(sha1)) {
RepositoryCache.assertFileChecksum(sha1, downloadPath, KeyType.SHA1);
}
if (isCaching) {
repositoryCache.put(sha1, downloadPath, KeyType.SHA1);
}
return downloadPath;
}Example 31
| Project: unity-maven-plugin-master File: DependencyGatherer.java View source code |
public List<ArtifactResult> resolveArtifacts() throws MojoFailureException {
CollectRequest collectRequest = new CollectRequest();
final Artifact mainArtifact = new DefaultArtifact(project.getArtifact().getId());
collectRequest.setRoot(new Dependency(mainArtifact, JavaScopes.COMPILE));
collectRequest.setRepositories(projectRepos);
DependencyRequest dependencyRequest = new DependencyRequest().setCollectRequest(collectRequest);
dependencyRequest.setFilter(new DependencyFilter() {
public boolean accept(DependencyNode node, List<DependencyNode> parents) {
Artifact nodeArtifact = node.getArtifact();
if (nodeArtifact.getGroupId().equals(mainArtifact.getGroupId()) && nodeArtifact.getArtifactId().equals(mainArtifact.getArtifactId())) {
return false;
}
return true;
}
});
List<ArtifactResult> resolvedArtifacts;
try {
resolvedArtifacts = repoSystem.resolveDependencies(repoSession, dependencyRequest).getArtifactResults();
} catch (DependencyResolutionException e) {
log.error("Could not resolve dependencies");
log.error(e.getMessage());
throw new MojoFailureException("Could not resolve dependencies");
}
return resolvedArtifacts;
}Example 32
| Project: aether-connector-okhttp-master File: AetherConnectorTest.java View source code |
public void testFileHandleLeakage() throws IOException, NoRepositoryConnectorException {
Artifact artifact = new DefaultArtifact("testGroup", "testArtifact", "", "jar", "1-test");
Metadata metadata = new DefaultMetadata("testGroup", "testArtifact", "1-test", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT);
RepositoryConnector connector = connector();
File tmpFile = TestFileUtils.createTempFile("testFileHandleLeakage");
ArtifactUpload artUp = new ArtifactUpload(artifact, tmpFile);
connector.put(Arrays.asList(artUp), null);
assertTrue("Leaking file handle in artifact upload", tmpFile.delete());
tmpFile = TestFileUtils.createTempFile("testFileHandleLeakage");
MetadataUpload metaUp = new MetadataUpload(metadata, tmpFile);
connector.put(null, Arrays.asList(metaUp));
assertTrue("Leaking file handle in metadata upload", tmpFile.delete());
tmpFile = TestFileUtils.createTempFile("testFileHandleLeakage");
ArtifactDownload artDown = new ArtifactDownload(artifact, null, tmpFile, null);
connector.get(Arrays.asList(artDown), null);
new File(tmpFile.getAbsolutePath() + ".sha1").deleteOnExit();
assertTrue("Leaking file handle in artifact download", tmpFile.delete());
tmpFile = TestFileUtils.createTempFile("testFileHandleLeakage");
MetadataDownload metaDown = new MetadataDownload(metadata, null, tmpFile, null);
connector.get(null, Arrays.asList(metaDown));
new File(tmpFile.getAbsolutePath() + ".sha1").deleteOnExit();
assertTrue("Leaking file handle in metadata download", tmpFile.delete());
connector.close();
}Example 33
| Project: appengine-maven-plugin-master File: SdkResolver.java View source code |
private static String determineNewestVersion(RepositorySystem repoSystem, RepositorySystemSession repoSession, List<RemoteRepository>[] repos) throws MojoExecutionException {
String version;
VersionRangeRequest rangeRequest = new VersionRangeRequest();
rangeRequest.setArtifact(new DefaultArtifact(SDK_GROUP_ID + ":" + SDK_ARTIFACT_ID + ":[0,)"));
for (List<RemoteRepository> repoList : repos) {
for (RemoteRepository repo : repoList) {
rangeRequest.addRepository(repo);
}
}
VersionRangeResult rangeResult;
try {
rangeResult = repoSystem.resolveVersionRange(repoSession, rangeRequest);
} catch (VersionRangeResolutionException e) {
throw new MojoExecutionException("Could not resolve latest version of the App Engine Java SDK", e);
}
List<Version> versions = rangeResult.getVersions();
Collections.sort(versions);
Version newest = Iterables.getLast(versions);
version = newest.toString();
return version;
}Example 34
| Project: b2-master File: MavenB2RequestFactory.java View source code |
private Artifact resolveArtifact(final MavenProject wrapperProject, String groupId, String artifactId, String extension, String version, String classifier) {
final org.eclipse.aether.artifact.Artifact siteArtifact = new DefaultArtifact(groupId, artifactId, classifier, extension, version);
ArtifactRequest request = new ArtifactRequest();
request.setArtifact(siteArtifact);
request.setRepositories(wrapperProject.getRemoteProjectRepositories());
try {
final ArtifactResult result = repositorySystem.resolveArtifact(legacySupport.getRepositorySession(), request);
return RepositoryUtils.toArtifact(result.getArtifact());
} catch (ArtifactResolutionException e) {
throw new IllegalStateException(e);
}
}Example 35
| Project: fabric3-gradle-test-plugins-master File: Fabric3TestTask.java View source code |
/**
* Creates the configuration to boot the Maven runtime, including resolving dependencies.
*
* @return the boot configuration
*/
private PluginBootConfiguration createBootConfiguration(TestPluginConvention convention, Resolver resolver, RepositorySystem system, RepositorySystemSession session) {
Project project = getProject();
configureWeb(convention);
try {
Set<Artifact> shared = convention.getShared();
Set<Project> sharedProjects = convention.getSharedProjects();
Set<Artifact> extensions = convention.getExtensions();
Set<Artifact> profiles = convention.getProfiles();
Set<Artifact> hostArtifacts = resolver.resolveHostArtifacts(shared);
Set<Artifact> runtimeArtifacts = resolver.resolveRuntimeArtifacts();
Artifact testExtension = new DefaultArtifact(FABRIC3_GRADLE, "test-extension", "jar", convention.getRuntimeVersion());
extensions.add(testExtension);
List<ContributionSource> runtimeExtensions = resolver.resolveRuntimeExtensions(extensions, profiles);
Set<URL> moduleDependencies = ProjectDependencies.calculateProjectDependencies(project, hostArtifacts, resolver);
ClassLoader parentClassLoader = createParentClassLoader();
URL[] sharedUrls = getSharedUrls(hostArtifacts, sharedProjects);
ClassLoader hostClassLoader = new DelegatingResourceClassLoader(sharedUrls, parentClassLoader);
ClassLoader bootClassLoader = ClassLoaderHelper.createBootClassLoader(hostClassLoader, runtimeArtifacts);
PluginBootConfiguration configuration = new PluginBootConfiguration();
configuration.setBootClassLoader(bootClassLoader);
configuration.setHostClassLoader(hostClassLoader);
DestinationRouter router = new PluginDestinationRouter(getLogger());
configuration.setRouter(router);
configuration.setExtensions(runtimeExtensions);
configuration.setModuleDependencies(moduleDependencies);
File buildDir = project.getBuildDir();
configuration.setOutputDirectory(buildDir);
if (convention.getSystemConfig() != null) {
configuration.setSystemConfig(convention.getSystemConfig());
} else if (convention.getSystemConfigFile() != null) {
InputStream is = new FileInputStream(convention.getSystemConfigFile());
ByteArrayOutputStream os = new ByteArrayOutputStream();
IOHelper.copy(is, os);
configuration.setSystemConfig(new String(os.toByteArray()));
}
configuration.setRepositorySession(session);
configuration.setRepositorySystem(system);
configuration.setBuildDir(project.getBuildDir());
return configuration;
} catch (DependencyResolutionExceptionArtifactResolutionException | IOException | e) {
throw new GradleException(e.getMessage(), e);
}
}Example 36
| Project: gcloud-maven-plugin-master File: SdkResolver.java View source code |
private static String determineNewestVersion(RepositorySystem repoSystem, RepositorySystemSession repoSession, List<RemoteRepository>[] repos) throws MojoExecutionException {
String version;
VersionRangeRequest rangeRequest = new VersionRangeRequest();
rangeRequest.setArtifact(new DefaultArtifact(SDK_GROUP_ID + ":" + SDK_ARTIFACT_ID + ":[0,)"));
for (List<RemoteRepository> repoList : repos) {
for (RemoteRepository repo : repoList) {
rangeRequest.addRepository(repo);
}
}
VersionRangeResult rangeResult;
try {
rangeResult = repoSystem.resolveVersionRange(repoSession, rangeRequest);
} catch (VersionRangeResolutionException e) {
throw new MojoExecutionException("Could not resolve latest version of the App Engine Java SDK", e);
}
List<Version> versions = rangeResult.getVersions();
Collections.sort(versions);
Version newest = Iterables.getLast(versions);
version = newest.toString();
return version;
}Example 37
| Project: LauncherCore-master File: MavenConnector.java View source code |
public boolean attemptLibraryDownload(String name, String url, DownloadListener listener) {
Dependency dependency = new Dependency(new DefaultArtifact(name), "compile");
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot(dependency);
if (url != null)
collectRequest.addRepository(new RemoteRepository.Builder("targetted", "default", url).build());
for (RemoteRepository repo : defaultRepositories) {
collectRequest.addRepository(repo);
}
try {
DependencyNode node = system.collectDependencies(session, collectRequest).getRoot();
DependencyRequest dependencyRequest = new DependencyRequest();
dependencyRequest.setRoot(node);
if (listener != null)
session.setTransferListener(new MavenListenerAdapter(listener));
system.resolveDependencies(session, dependencyRequest);
return true;
} catch (DependencyCollectionException ex) {
return false;
} catch (DependencyResolutionException ex) {
return false;
}
}Example 38
| Project: liferay-ide-master File: LiferayMavenProjectProvider.java View source code |
@Override
public <T> List<T> getData(String key, Class<T> type, Object... params) {
List<T> retval = null;
if ("profileIds".equals(key)) {
final List<T> profileIds = new ArrayList<T>();
try {
final List<Profile> profiles = MavenPlugin.getMaven().getSettings().getProfiles();
for (final Profile profile : profiles) {
if (profile.getActivation() != null) {
if (profile.getActivation().isActiveByDefault()) {
continue;
}
}
profileIds.add(type.cast(profile.getId()));
}
if (params[0] != null && params[0] instanceof File) {
final File locationDir = (File) params[0];
File pomFile = new File(locationDir, IMavenConstants.POM_FILE_NAME);
if (!pomFile.exists() && locationDir.getParentFile().exists()) {
// try one level up for when user is adding new module
pomFile = new File(locationDir.getParentFile(), IMavenConstants.POM_FILE_NAME);
}
if (pomFile.exists()) {
final IMaven maven = MavenPlugin.getMaven();
Model model = maven.readModel(pomFile);
File parentDir = pomFile.getParentFile();
while (model != null) {
for (org.apache.maven.model.Profile p : model.getProfiles()) {
profileIds.add(type.cast(p.getId()));
}
parentDir = parentDir.getParentFile();
if (parentDir != null && parentDir.exists()) {
try {
model = maven.readModel(new File(parentDir, IMavenConstants.POM_FILE_NAME));
} catch (Exception e) {
model = null;
}
}
}
}
}
} catch (CoreException e) {
LiferayMavenCore.logError(e);
}
retval = profileIds;
} else if ("liferayVersions".equals(key)) {
final List<T> possibleVersions = new ArrayList<T>();
final RepositorySystem system = AetherUtil.newRepositorySystem();
final RepositorySystemSession session = AetherUtil.newRepositorySystemSession(system);
final String groupId = params[0].toString();
final String artifactId = params[1].toString();
final String coords = groupId + ":" + artifactId + ":[6,)";
final Artifact artifact = new DefaultArtifact(coords);
final VersionRangeRequest rangeRequest = new VersionRangeRequest();
rangeRequest.setArtifact(artifact);
rangeRequest.addRepository(AetherUtil.newCentralRepository());
rangeRequest.addRepository(AetherUtil.newLiferayRepository());
try {
final VersionRangeResult rangeResult = system.resolveVersionRange(session, rangeRequest);
final List<Version> versions = rangeResult.getVersions();
for (Version version : versions) {
final String val = version.toString();
if (!"6.2.0".equals(val)) {
possibleVersions.add(type.cast(val));
}
}
retval = possibleVersions;
} catch (VersionRangeResolutionException e) {
}
} else if ("parentVersion".equals(key)) {
final List<T> version = new ArrayList<T>();
final File locationDir = (File) params[0];
final File parentPom = new File(locationDir, IMavenConstants.POM_FILE_NAME);
if (parentPom.exists()) {
try {
final IMaven maven = MavenPlugin.getMaven();
final Model model = maven.readModel(parentPom);
version.add(type.cast(model.getVersion()));
retval = version;
} catch (CoreException e) {
LiferayMavenCore.logError("unable to get parent version", e);
}
}
} else if ("parentGroupId".equals(key)) {
final List<T> groupId = new ArrayList<T>();
final File locationDir = (File) params[0];
final File parentPom = new File(locationDir, IMavenConstants.POM_FILE_NAME);
if (parentPom.exists()) {
try {
final IMaven maven = MavenPlugin.getMaven();
final Model model = maven.readModel(parentPom);
groupId.add(type.cast(model.getGroupId()));
retval = groupId;
} catch (CoreException e) {
LiferayMavenCore.logError("unable to get parent groupId", e);
}
}
} else if ("archetypeGAV".equals(key)) {
final String frameworkType = (String) params[0];
final String value = LiferayMavenCore.getPreferenceString("archetype-gav-" + frameworkType, "");
retval = Collections.singletonList(type.cast(value));
}
return retval;
}Example 39
| Project: liferay-portal-master File: BuildThemeMojo.java View source code |
private Artifact _resolveArtifact(ComponentDependency componentDependency) throws ArtifactResolutionException {
Artifact artifact = new DefaultArtifact(componentDependency.getGroupId(), componentDependency.getArtifactId(), componentDependency.getType(), componentDependency.getVersion());
ArtifactRequest artifactRequest = new ArtifactRequest();
artifactRequest.setArtifact(artifact);
List<RemoteRepository> repositories = new ArrayList<>();
repositories.addAll(_project.getRemotePluginRepositories());
repositories.addAll(_project.getRemoteProjectRepositories());
artifactRequest.setRepositories(repositories);
ArtifactResult artifactResult = _repositorySystem.resolveArtifact(_repositorySystemSession, artifactRequest);
return artifactResult.getArtifact();
}Example 40
| Project: maven-shared-master File: Maven31DependencyResolver.java View source code |
@Override
public // CHECKSTYLE_OFF: LineLength
Iterable<org.apache.maven.shared.artifact.resolve.ArtifactResult> resolveDependencies(ProjectBuildingRequest buildingRequest, Model model, TransformableFilter dependencyFilter) throws // CHECKSTYLE_ON: LineLength
DependencyResolverException {
// Are there examples where packaging and type are NOT in sync
ArtifactHandler artifactHandler = artifactHandlerManager.getArtifactHandler(model.getPackaging());
String extension = artifactHandler != null ? artifactHandler.getExtension() : null;
Artifact aetherArtifact = new DefaultArtifact(model.getGroupId(), model.getArtifactId(), extension, model.getVersion());
Dependency aetherRoot = new Dependency(aetherArtifact, null);
@SuppressWarnings("unchecked") List<RemoteRepository> aetherRepositories = (List<RemoteRepository>) Invoker.invoke(RepositoryUtils.class, "toRepos", List.class, buildingRequest.getRemoteRepositories());
CollectRequest request = new CollectRequest(aetherRoot, aetherRepositories);
ArtifactTypeRegistry typeRegistry = (ArtifactTypeRegistry) Invoker.invoke(RepositoryUtils.class, "newArtifactTypeRegistry", ArtifactHandlerManager.class, artifactHandlerManager);
List<Dependency> aetherDependencies = new ArrayList<Dependency>(model.getDependencies().size());
for (org.apache.maven.model.Dependency mavenDependency : model.getDependencies()) {
aetherDependencies.add(toDependency(mavenDependency, typeRegistry));
}
request.setDependencies(aetherDependencies);
DependencyManagement mavenDependencyManagement = model.getDependencyManagement();
if (mavenDependencyManagement != null) {
List<Dependency> aetherManagerDependencies = new ArrayList<Dependency>(mavenDependencyManagement.getDependencies().size());
for (org.apache.maven.model.Dependency mavenDependency : mavenDependencyManagement.getDependencies()) {
aetherManagerDependencies.add(toDependency(mavenDependency, typeRegistry));
}
request.setManagedDependencies(aetherManagerDependencies);
}
return resolveDependencies(buildingRequest, aetherRepositories, dependencyFilter, request);
}Example 41
| Project: nonsnapshot-maven-plugin-master File: UpstreamDependencyHandlerDefaultImpl.java View source code |
@Override
public String resolveLatestVersion(MavenArtifact mavenArtifact, ProcessedUpstreamDependency upstreamDependency, RepositorySystem repositorySystem, RepositorySystemSession repositorySystemSession, List<RemoteRepository> remoteRepositories) throws NonSnapshotDependencyResolverException {
String currentVersion = mavenArtifact.getVersion();
if (currentVersion.contains("$")) {
currentVersion = "0.0.0";
} else if (currentVersion.endsWith("-SNAPSHOT")) {
currentVersion = currentVersion.split("-")[0];
}
String versionPrefix;
String versionQuery;
if (upstreamDependency.getVersionIncrement() != null) {
versionPrefix = upstreamDependency.getVersionMajor() + "." + upstreamDependency.getVersionMinor() + "." + upstreamDependency.getVersionIncrement();
String nextIncrement = upstreamDependency.getVersionMajor() + "." + upstreamDependency.getVersionMinor() + "." + (upstreamDependency.getVersionIncrement() + 1);
versionQuery = mavenArtifact.getGroupId() + ":" + mavenArtifact.getArtifactId() + ":(" + currentVersion + "," + nextIncrement + ")";
} else if (upstreamDependency.getVersionMinor() != null) {
versionPrefix = upstreamDependency.getVersionMajor() + "." + upstreamDependency.getVersionMinor();
String nextMinor = upstreamDependency.getVersionMajor() + "." + (upstreamDependency.getVersionMinor() + 1) + ".0";
versionQuery = mavenArtifact.getGroupId() + ":" + mavenArtifact.getArtifactId() + ":(" + currentVersion + "," + nextMinor + ")";
} else if (upstreamDependency.getVersionMajor() != null) {
versionPrefix = String.valueOf(upstreamDependency.getVersionMajor());
String nextMajor = (upstreamDependency.getVersionMajor() + 1) + ".0.0";
versionQuery = mavenArtifact.getGroupId() + ":" + mavenArtifact.getArtifactId() + ":(" + currentVersion + "," + nextMajor + ")";
} else {
versionPrefix = "";
versionQuery = mavenArtifact.getGroupId() + ":" + mavenArtifact.getArtifactId() + ":(" + currentVersion + ",)";
}
Artifact aetherArtifact = new DefaultArtifact(versionQuery);
VersionRangeRequest rangeRequest = new VersionRangeRequest();
rangeRequest.setArtifact(aetherArtifact);
rangeRequest.setRepositories(remoteRepositories);
try {
LOG.debug("Resolving versions for {}", versionQuery);
VersionRangeResult result = repositorySystem.resolveVersionRange(repositorySystemSession, rangeRequest);
LOG.debug("Found versions for {}: {}", versionQuery, result);
List<Version> versions = result.getVersions();
Collections.reverse(versions);
for (Version version : versions) {
String versionStr = version.toString();
if (!versionStr.endsWith("-SNAPSHOT") && versionStr.startsWith(versionPrefix)) {
return versionStr;
}
}
return null;
} catch (VersionRangeResolutionException e) {
throw new NonSnapshotDependencyResolverException("Couldn't resolve latest upstream version for: " + versionQuery + ". Keeping current version " + currentVersion, e);
}
}Example 42
| Project: org.ops4j.pax.url-master File: AetherBasedResolver.java View source code |
private File resolve(List<LocalRepository> defaultRepos, List<RemoteRepository> remoteRepos, Artifact artifact) throws IOException {
if (artifact.getExtension().isEmpty()) {
artifact = new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(), "jar", artifact.getVersion());
}
// Try with default repositories
try {
VersionConstraint vc = new GenericVersionScheme().parseVersionConstraint(artifact.getVersion());
if (vc.getVersion() != null) {
for (LocalRepository repo : defaultRepos) {
RepositorySystemSession session = newSession(repo);
try {
return m_repoSystem.resolveArtifact(session, new ArtifactRequest(artifact, null, null)).getArtifact().getFile();
} catch (ArtifactResolutionException e) {
} finally {
releaseSession(session);
}
}
}
} catch (InvalidVersionSpecificationException e) {
}
RepositorySystemSession session = newSession(null);
try {
artifact = resolveLatestVersionRange(session, remoteRepos, artifact);
return m_repoSystem.resolveArtifact(session, new ArtifactRequest(artifact, remoteRepos, null)).getArtifact().getFile();
} catch (ArtifactResolutionException e) {
ArtifactResolutionException original = new ArtifactResolutionException(e.getResults(), "Error resolving artifact " + artifact.toString(), null);
original.setStackTrace(e.getStackTrace());
List<String> messages = new ArrayList<>(e.getResult().getExceptions().size());
List<Exception> suppressed = new ArrayList<>();
for (Exception ex : e.getResult().getExceptions()) {
messages.add(ex.getMessage() == null ? ex.getClass().getName() : ex.getMessage());
suppressed.add(ex);
}
IOException exception = new IOException(original.getMessage() + ": " + messages, original);
for (Exception ex : suppressed) {
exception.addSuppressed(ex);
}
LOG.warn(exception.getMessage(), exception);
throw exception;
} catch (RepositoryException e) {
throw new IOException("Error resolving artifact " + artifact.toString(), e);
} finally {
releaseSession(session);
}
}Example 43
| Project: resolver-master File: MavenConverter.java View source code |
/**
* Converts Maven {@link org.apache.maven.model.Dependency} to Aether {@link org.eclipse.aether.graph.Dependency}
*
* @param dependency
* the Maven dependency to be converted
* @param registry
* the Artifact type catalog to determine common artifact properties
* @return Equivalent Aether dependency
*/
public static MavenDependency fromDependency(org.apache.maven.model.Dependency dependency, ArtifactTypeRegistry registry) {
ArtifactType stereotype = registry.get(dependency.getType());
if (stereotype == null) {
stereotype = new DefaultArtifactType(dependency.getType());
}
boolean system = dependency.getSystemPath() != null && dependency.getSystemPath().length() > 0;
Map<String, String> props = null;
if (system) {
props = Collections.singletonMap(ArtifactProperties.LOCAL_PATH, dependency.getSystemPath());
}
Artifact artifact = new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(), dependency.getClassifier(), null, dependency.getVersion(), props, stereotype);
Set<MavenDependencyExclusion> exclusions = new LinkedHashSet<MavenDependencyExclusion>();
for (org.apache.maven.model.Exclusion e : dependency.getExclusions()) {
exclusions.add(fromExclusion(e));
}
final PackagingType packaging = PackagingType.of(artifact.getProperty(ArtifactProperties.TYPE, artifact.getExtension()));
final String classifier = artifact.getClassifier().length() == 0 ? packaging.getClassifier() : artifact.getClassifier();
final MavenCoordinate coordinate = MavenCoordinates.createCoordinate(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), packaging, classifier);
// SHRINKRES-123 Allow for depMgt explicitly not setting scope
final String resolvedScope = dependency.getScope();
final boolean undeclaredScope = resolvedScope == null;
// SHRINKRES-143 lets ignore invalid scope
ScopeType scope = ScopeType.RUNTIME;
try {
scope = ScopeType.fromScopeType(resolvedScope);
} catch (IllegalArgumentException e) {
log.log(Level.WARNING, "Invalid scope {0} of dependency {1} will be replaced by <scope>runtime</scope>", new Object[] { dependency.getScope(), coordinate.toCanonicalForm() });
}
final MavenDependencySPI result = new MavenDependencyImpl(coordinate, scope, dependency.isOptional(), undeclaredScope, exclusions.toArray(TYPESAFE_EXCLUSIONS_ARRAY));
return result;
}Example 44
| Project: revapi-master File: Analyzer.java View source code |
/**
* Resolves the gav using the resolver. If the gav corresponds to the project artifact and is an unresolved version
* for a RELEASE or LATEST, the gav is resolved such it a release not newer than the project version is found that
* optionally corresponds to the provided version regex, if provided.
*
* <p>If the gav exactly matches the current project, the file of the artifact is found on the filesystem in
* target directory and the resolver is ignored.
*
* @param project the project to restrict by, if applicable
* @param gav the gav to resolve
* @param versionRegex the optional regex the version must match to be considered.
* @param resolver the version resolver to use
* @return the resolved artifact matching the criteria.
*
* @throws VersionRangeResolutionException on error
* @throws ArtifactResolutionException on error
*/
static Artifact resolveConstrained(MavenProject project, String gav, Pattern versionRegex, ArtifactResolver resolver) throws VersionRangeResolutionException, ArtifactResolutionException {
if (gav.endsWith(":RELEASE") || gav.endsWith(":LATEST")) {
versionRegex = versionRegex == null ? ANY_NON_SNAPSHOT : versionRegex;
Artifact a = new DefaultArtifact(gav);
String upTo = project.getGroupId().equals(a.getGroupId()) && project.getArtifactId().equals(a.getArtifactId()) ? project.getVersion() : null;
return resolver.resolveNewestMatching(gav, upTo, versionRegex);
} else {
String projectGav = getProjectArtifactCoordinates(project, null);
Artifact ret = null;
if (projectGav.equals(gav)) {
ret = findProjectArtifact(project);
}
return ret == null ? resolver.resolveArtifact(gav) : ret;
}
}Example 45
| Project: vertx-mod-webjar-master File: WebjarPullerVerticle.java View source code |
private List<Dependency> getDependencies(JsonArray webjars) {
List<Dependency> dependencies = new ArrayList<>();
for (int i = 0; i < webjars.size(); i++) {
String artifactGav = webjars.get(i);
Artifact artifact = new DefaultArtifact(artifactGav);
Dependency dependency = new Dependency(artifact, JavaScopes.COMPILE);
dependencies.add(dependency);
}
return dependencies;
}Example 46
| Project: artifact-promotion-plugin-master File: AetherInteraction.java View source code |
/** Get ('resolve') the artifact from a repository server.
* If the artifact is in local repository used by the plugin it will not
* download it from the server and use the local silently. This local repo
* will be cleaned by 'mvn clean' as the default location is target/local-repo.
*
* @param session
* @param system
* @param remoteRepos
* @param groupId
* @param artifactId
* @param classifier
* @param type
* @param version
* @return
* @throws ArtifactResolutionException
*/
protected Artifact getArtifact(final RepositorySystemSession session, RepositorySystem system, final RemoteRepository remoteRepo, final String groupId, final String artifactId, final String classifier, final String type, final String version) throws ArtifactResolutionException {
Artifact artifact = new DefaultArtifact(groupId, artifactId, classifier, type, version);
ArtifactRequest artifactRequest = new ArtifactRequest();
artifactRequest.setArtifact(artifact);
artifactRequest.setRepositories(new ArrayList<RemoteRepository>(Arrays.asList(remoteRepo)));
ArtifactResult artifactResult = system.resolveArtifact(session, artifactRequest);
artifact = artifactResult.getArtifact();
return artifact;
}Example 47
| Project: camel-master File: BOMResolver.java View source code |
private void retrieveUpstreamBOMVersions() throws Exception {
RepositorySystem system = newRepositorySystem();
DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
LocalRepository localRepo = new LocalRepository(LOCAL_REPO);
session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));
String camelVersion = DependencyResolver.resolveCamelParentProperty("${project.version}");
List<Artifact> neededArtifacts = new LinkedList<>();
neededArtifacts.add(new DefaultArtifact("org.apache.camel:camel:pom:" + camelVersion).setFile(camelRoot("pom.xml")));
neededArtifacts.add(new DefaultArtifact("org.apache.camel:camel-parent:pom:" + camelVersion).setFile(camelRoot("parent/pom.xml")));
neededArtifacts.add(new DefaultArtifact("org.apache.camel:spring-boot:pom:" + camelVersion).setFile(camelRoot("platforms/spring-boot/pom.xml")));
neededArtifacts.add(new DefaultArtifact("org.apache.camel:camel-spring-boot-dm:pom:" + camelVersion).setFile(camelRoot("platforms/spring-boot/spring-boot-dm/pom.xml")));
neededArtifacts.add(new DefaultArtifact("org.apache.camel:camel-spring-boot-dependencies:pom:" + camelVersion).setFile(camelRoot("platforms/spring-boot/spring-boot-dm/camel-spring-boot-dependencies/pom.xml")));
Artifact camelSpringBootParent = new DefaultArtifact("org.apache.camel:camel-starter-parent:pom:" + camelVersion).setFile(camelRoot("platforms/spring-boot/spring-boot-dm/camel-starter-parent/pom.xml"));
neededArtifacts.add(camelSpringBootParent);
RemoteRepository localRepoDist = new RemoteRepository.Builder("org.apache.camel.itest.springboot", "default", new File(LOCAL_REPO).toURI().toString()).build();
for (Artifact artifact : neededArtifacts) {
DeployRequest deployRequest = new DeployRequest();
deployRequest.addArtifact(artifact);
deployRequest.setRepository(localRepoDist);
system.deploy(session, deployRequest);
}
RemoteRepository mavenCentral = new RemoteRepository.Builder("central", "default", "http://repo1.maven.org/maven2/").build();
RemoteRepository apacheSnapshots = new RemoteRepository.Builder("apache-snapshots", "default", "http://repository.apache.org/snapshots/").build();
ArtifactDescriptorRequest dReq = new ArtifactDescriptorRequest(camelSpringBootParent, Arrays.asList(localRepoDist, mavenCentral, apacheSnapshots), null);
ArtifactDescriptorResult dRes = system.readArtifactDescriptor(session, dReq);
this.versions = new TreeMap<>();
for (Dependency dependency : dRes.getManagedDependencies()) {
Artifact a = dependency.getArtifact();
String key = a.getGroupId() + ":" + a.getArtifactId();
versions.put(key, dependency.getArtifact().getVersion());
}
}Example 48
| Project: fabric3-plugins-master File: Fabric3RuntimeAssemblyMojo.java View source code |
/**
* Resolves and unzips the contents of a base runtime distribution to a directory.
*
* @param groupId the distribution group id
* @param artifactId the distribution artifact id
* @param baseDirectory the extract directory
* @throws MojoExecutionException if there is an error extracting the distribution
*/
private void extractRuntime(String groupId, String artifactId, File baseDirectory) throws MojoExecutionException {
Artifact artifact = new DefaultArtifact(groupId, artifactId, "bin", "zip", runtimeVersion);
try {
getLog().info("Installing the Fabric3 runtime");
ArtifactResult result = repositorySystem.resolveArtifact(session, new ArtifactRequest(artifact, projectRepositories, null));
File source = result.getArtifact().getFile();
extract(source, baseDirectory);
} catch (ArtifactResolutionException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}Example 49
| Project: guvnor-master File: GuvnorM2Repository.java View source code |
public void deployParentPom(final GAV gav) {
//Write pom.xml to temporary file for deployment
final File pomXMLFile = new File(System.getProperty("java.io.tmpdir"), toFileName(gav, "pom.xml"));
try {
String pomXML = generateParentPOM(gav);
writeStringIntoFile(pomXML, pomXMLFile);
//pom.xml Artifact
Artifact pomXMLArtifact = new DefaultArtifact(gav.getGroupId(), gav.getArtifactId(), "pom", gav.getVersion());
pomXMLArtifact = pomXMLArtifact.setFile(pomXMLFile);
final Artifact finalPomXMLArtifact = pomXMLArtifact;
this.pomRepositories.forEach( artifactRepository -> {
artifactRepository.deploy(pomXML, finalPomXMLArtifact);
});
} finally {
try {
pomXMLFile.delete();
} catch (Exception e) {
log.warn("Unable to remove temporary file '" + pomXMLFile.getAbsolutePath() + "'");
}
}
}Example 50
| Project: intellij-community-master File: ArtifactRepositoryManager.java View source code |
private static List<Artifact> toArtifacts(String groupId, String artifactId, Collection<VersionConstraint> constraints, Set<ArtifactKind> kinds) {
if (constraints.isEmpty() || kinds.isEmpty()) {
return Collections.emptyList();
}
final List<Artifact> result = new ArrayList<>(kinds.size() * constraints.size());
for (ArtifactKind kind : kinds) {
for (VersionConstraint constr : constraints) {
result.add(new DefaultArtifact(groupId, artifactId, kind.getClassifier(), kind.getExtension(), constr.toString()));
}
}
return result;
}Example 51
| Project: jaxrs-analyzer-maven-plugin-master File: JAXRSAnalyzerMojo.java View source code |
private Path fetchDependency(final String artifactIdentifier) throws MojoExecutionException {
ArtifactRequest request = new ArtifactRequest();
final DefaultArtifact artifact = new DefaultArtifact(artifactIdentifier);
request.setArtifact(artifact);
request.setRepositories(remoteRepos);
LogProvider.debug("Resolving artifact " + artifact + " from " + remoteRepos);
ArtifactResult result;
try {
result = repoSystem.resolveArtifact(repoSession, request);
} catch (ArtifactResolutionException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
LogProvider.debug("Resolved artifact " + artifact + " to " + result.getArtifact().getFile() + " from " + result.getRepository());
return result.getArtifact().getFile().toPath();
}Example 52
| Project: moditect-master File: GenerateModuleInfoMojo.java View source code |
private void processModule(ModuleConfiguration moduleConfiguration) throws MojoExecutionException {
Artifact inputArtifact = resolveArtifact(new DefaultArtifact(moduleConfiguration.getArtifact().toDependencyString()));
Set<DependencyDescriptor> dependencies = getDependencies(inputArtifact);
for (ArtifactConfiguration further : moduleConfiguration.getAdditionalDependencies()) {
Artifact furtherArtifact = resolveArtifact(new DefaultArtifact(further.toDependencyString()));
dependencies.add(new DependencyDescriptor(furtherArtifact.getFile().toPath(), false));
}
new GenerateModuleInfo(inputArtifact.getFile().toPath(), moduleConfiguration.getModuleName(), dependencies, moduleConfiguration.getExportExcludes().stream().map( e -> Pattern.compile(e)).collect(Collectors.toList()), workingDirectory.toPath(), outputDirectory.toPath(), moduleConfiguration.isAddServiceUses(), new MojoLog(getLog())).run();
}Example 53
| Project: onos-master File: AetherResolver.java View source code |
private BuckArtifact build(String name, String uri) {
uri = uri.replaceFirst("mvn:", "");
Artifact artifact = new DefaultArtifact(uri);
String originalVersion = artifact.getVersion();
try {
artifact = artifact.setVersion(newestVersion(artifact));
artifact = resolveArtifact(artifact);
String sha = getSha(artifact);
boolean osgiReady = isOsgiReady(artifact);
if (originalVersion.endsWith("-SNAPSHOT")) {
String url = String.format("%s/%s/%s/%s/%s-%s.%s", repoUrl, artifact.getGroupId().replace('.', '/'), artifact.getArtifactId(), originalVersion, artifact.getArtifactId(), artifact.getVersion(), artifact.getExtension());
String mavenCoords = String.format("%s:%s:%s", artifact.getGroupId(), artifact.getArtifactId(), originalVersion);
return BuckArtifact.getArtifact(name, url, sha, mavenCoords, osgiReady);
}
return BuckArtifact.getArtifact(name, artifact, sha, repoUrl, osgiReady);
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 54
| Project: roboconf-platform-master File: ResolveMojo.java View source code |
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
// Find the target directory
File completeAppDirectory = new File(this.project.getBuild().getOutputDirectory());
// Copy the dependencies resources in the target directory
Set<Artifact> artifacts = new HashSet<>();
if (this.project.getDependencyArtifacts() != null)
artifacts.addAll(this.project.getDependencyArtifacts());
for (Artifact unresolvedArtifact : artifacts) {
// Here, it becomes messy. We ask Maven to resolve the artifact's location.
// It may imply downloading it from a remote repository,
// searching the local repository or looking into the reactor's cache.
// To achieve this, we must use Aether
// (the dependency mechanism behind Maven).
String artifactId = unresolvedArtifact.getArtifactId();
org.eclipse.aether.artifact.Artifact aetherArtifact = new DefaultArtifact(unresolvedArtifact.getGroupId(), unresolvedArtifact.getArtifactId(), unresolvedArtifact.getClassifier(), unresolvedArtifact.getType(), unresolvedArtifact.getVersion());
ArtifactRequest req = new ArtifactRequest().setRepositories(this.repositories).setArtifact(aetherArtifact);
ArtifactResult resolutionResult;
try {
resolutionResult = this.repoSystem.resolveArtifact(this.repoSession, req);
} catch (ArtifactResolutionException e) {
throw new MojoExecutionException("Artifact " + artifactId + " could not be resolved.", e);
}
// The file should exists, but we never know.
File file = resolutionResult.getArtifact().getFile();
if (file == null || !file.exists()) {
getLog().warn("Artifact " + artifactId + " has no attached file. Its content will not be copied in the target model directory.");
continue;
}
// Prepare the extraction
File targetDirectory = new File(completeAppDirectory, Constants.PROJECT_DIR_GRAPH + "/" + artifactId);
getLog().debug("Copying the content of artifact " + artifactId + " under " + targetDirectory);
try {
// Extract graph files - assumed to be at the root of the graph directory
Utils.extractZipArchive(file, targetDirectory, "graph/[^/]*\\.graph", "graph/");
// Extract component files - directories
Utils.extractZipArchive(file, targetDirectory.getParentFile(), "graph/.*/.*", "graph/");
} catch (IOException e) {
throw new MojoExecutionException("The ZIP archive for artifact " + artifactId + " could not be extracted.", e);
}
// Do they contain target definitions?
// This is only to display a warning candidate, in case where the imported artifact
// would contain target properties. Indeed, such properties may result in conflicts
// when imported by several application templates. They should instead be packaged separately.
File temporaryDirectory = new File(System.getProperty("java.io.tmpdir"), "roboconf-temp");
try {
Utils.extractZipArchive(file, temporaryDirectory);
ApplicationLoadResult alr = RuntimeModelIo.loadApplicationFlexibly(temporaryDirectory);
if (alr.getApplicationTemplate().getGraphs() != null) {
for (File dir : ResourceUtils.findScopedInstancesDirectories(alr.getApplicationTemplate()).values()) {
if (Utils.listAllFiles(dir).isEmpty())
continue;
getLog().warn("Artifact " + artifactId + " contains target properties. Reusable target properties should be packaged separately.");
}
}
} catch (IOException e) {
getLog().debug("The presence of target properties in the " + artifactId + " artifact could not be verified.");
} finally {
Utils.deleteFilesRecursivelyAndQuietly(temporaryDirectory);
}
}
}Example 55
| Project: sisu-maven-bridge-master File: MavenDependencyTreeResolverSupport.java View source code |
private Dependency toDependency(final org.apache.maven.model.Dependency dependency, final ArtifactTypeRegistry stereotypes) {
ArtifactType stereotype = stereotypes.get(dependency.getType());
if (stereotype == null) {
stereotype = new DefaultArtifactType(dependency.getType());
}
final boolean system = dependency.getSystemPath() != null && dependency.getSystemPath().length() > 0;
Map<String, String> props = null;
if (system) {
props = Collections.singletonMap(ArtifactProperties.LOCAL_PATH, dependency.getSystemPath());
}
final Artifact artifact = new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(), dependency.getClassifier(), null, dependency.getVersion(), props, stereotype);
final List<Exclusion> exclusions = new ArrayList<Exclusion>(dependency.getExclusions().size());
for (final org.apache.maven.model.Exclusion exclusion : dependency.getExclusions()) {
exclusions.add(toExclusion(exclusion));
}
return new Dependency(artifact, dependency.getScope(), dependency.isOptional(), exclusions);
}Example 56
| Project: sundrio-master File: ExternalBomResolver.java View source code |
private Map<Artifact, Dependency> resolveDependencies(BomImport bom) throws Exception {
org.eclipse.aether.artifact.Artifact artifact = new org.eclipse.aether.artifact.DefaultArtifact(bom.getGroupId(), bom.getArtifactId(), "pom", bom.getVersion());
List<RemoteRepository> repositories = remoteRepositories;
if (bom.getRepository() != null) {
// Include the additional repository into the copy
repositories = new LinkedList<RemoteRepository>(repositories);
RemoteRepository repo = new RemoteRepository.Builder(bom.getArtifactId() + "-repository", "default", bom.getRepository()).build();
repositories.add(0, repo);
}
ArtifactRequest artifactRequest = new ArtifactRequest(artifact, repositories, null);
// To get an error when the artifact does not exist
system.resolveArtifact(session, artifactRequest);
ArtifactDescriptorRequest req = new ArtifactDescriptorRequest(artifact, repositories, null);
ArtifactDescriptorResult res = system.readArtifactDescriptor(session, req);
Map<Artifact, Dependency> mavenDependencies = new LinkedHashMap<Artifact, Dependency>();
if (res.getManagedDependencies() != null) {
for (org.eclipse.aether.graph.Dependency dep : res.getManagedDependencies()) {
mavenDependencies.put(toMavenArtifact(dep), toMavenDependency(dep));
}
}
return mavenDependencies;
}Example 57
| Project: wildfly-swarm-master File: MavenArtifactResolvingHelper.java View source code |
@Override
public ArtifactSpec resolve(ArtifactSpec spec) {
if (spec.file == null) {
final DefaultArtifact artifact = new DefaultArtifact(spec.groupId(), spec.artifactId(), spec.classifier(), spec.type(), spec.version());
final LocalArtifactResult localResult = this.session.getLocalRepositoryManager().find(this.session, new LocalArtifactRequest(artifact, this.remoteRepositories, null));
if (localResult.isAvailable()) {
spec.file = localResult.getFile();
} else {
try {
final ArtifactResult result = resolver.resolveArtifact(this.session, new ArtifactRequest(artifact, this.remoteRepositories, null));
if (result.isResolved()) {
spec.file = result.getArtifact().getFile();
}
} catch (ArtifactResolutionException e) {
e.printStackTrace();
}
}
}
return spec.file != null ? spec : null;
}Example 58
| Project: wisdom-master File: DependencyFinder.java View source code |
/**
* Resolves the specified artifact (using its GAV, classifier and packaging).
*
* @param mojo the mojo
* @param groupId the groupId of the artifact to resolve
* @param artifactId the artifactId of the artifact to resolve
* @param version the version
* @param type the type
* @param classifier the classifier
* @return the artifact's file if it can be revolved. The file is located in the local maven repository.
* @throws MojoExecutionException if the artifact cannot be resolved
*/
public static File resolve(AbstractWisdomMojo mojo, String groupId, String artifactId, String version, String type, String classifier) throws MojoExecutionException {
ArtifactRequest request = new ArtifactRequest();
request.setArtifact(new DefaultArtifact(groupId, artifactId, classifier, type, version));
request.setRepositories(mojo.remoteRepos);
mojo.getLog().info("Resolving artifact " + artifactId + " from " + mojo.remoteRepos);
ArtifactResult result;
try {
result = mojo.repoSystem.resolveArtifact(mojo.repoSession, request);
} catch (ArtifactResolutionException e) {
mojo.getLog().error("Cannot resolve " + groupId + ":" + artifactId + ":" + version + ":" + type);
throw new MojoExecutionException(e.getMessage(), e);
}
mojo.getLog().info("Resolved artifact " + artifactId + " to " + result.getArtifact().getFile() + " from " + result.getRepository());
return result.getArtifact().getFile();
}Example 59
| Project: xapi-master File: AbstractXapiMojo.java View source code |
@Override
protected File initialValue() {
Preconditions.checkNotNull(targetProject, "You must supply a ${target.project} configuration property " + "in order to use any service methods which depend upon #getTargetPom().");
boolean endsWithXml = targetProject.endsWith(".xml");
// first, check for absolute file.
File targetFile = new File(targetProject);
try {
targetFile = targetFile.getCanonicalFile();
} catch (IOException ignored) {
}
if (endsWithXml && targetFile.exists()) {
targetFile = targetFile.getParentFile();
}
if (targetFile.isDirectory()) {
return targetFile;
}
try {
// okay, no absolute file. Now check relative to source root.
targetFile = new File(sourceRoot.getCanonicalFile(), targetProject);
if (targetFile.exists()) {
return targetFile.getParentFile();
}
} catch (IOException ignored) {
}
// Assume maven artifact
String[] bits = targetProject.split(":", -1);
if (bits.length < 2) {
throw new AssertionError("The target.project you supplied, " + targetProject + ", is neither the " + "location of a pom file (*.xml)," + " nor a maven artifact (groupId:artifactId:extension:version)");
}
DefaultArtifact artifact;
if (bits.length == 2) {
Preconditions.checkArgument(bits[0].equals(X_Namespace.XAPI_GROUP_ID), "Unless your target artifact, " + targetProject + " begins with group Id, " + X_Namespace.XAPI_GROUP_ID + ", you must supply, at the very least, groupId:artifactId:version");
artifact = new DefaultArtifact(targetProject + ":" + X_Namespace.XAPI_VERSION);
} else {
artifact = new DefaultArtifact(targetProject);
}
// resolve artifacts
if (workspace != null) {
File result = workspace.findArtifact(artifact);
X_Log.info(getClass(), "Searching for target project directory from", result, "derived from artifact", artifact);
if (result != null) {
return result.getParentFile().getParentFile();
}
// If we couldn't find the artifact directly from the workspace, we need to
// look up the pom tree to the root, build all modules, and find the correct artifact.
MavenProject root = getSession().getCurrentProject();
while (root.getParent() != null) {
root = root.getParent();
}
try {
DefaultProjectBuildingRequest req = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
req.setProject(root);
req.setResolveDependencies(true);
List<File> poms = new ArrayList<File>();
poms.add(new File(root.getBasedir(), "pom.xml"));
List<ProjectBuildingResult> res = builder.build(poms, true, req);
for (ProjectBuildingResult proj : res) {
String ident = proj.getProject().getArtifact().getId();
if (ident.startsWith(targetProject)) {
if (ident.equals(targetProject) || ident.startsWith(targetProject + ":")) {
return proj.getProject().getBasedir();
}
}
}
} catch (ProjectBuildingException e) {
e.printStackTrace();
}
}
throw new RuntimeException("Could not find pom file for " + targetProject + "; if you wish to target a project outside your " + "maven workspace, you must specify the full location of the project pom" + " (using groupId:artifactId only works if the given project " + "is accessible to WorkspaceReader)");
}Example 60
| Project: buck-master File: Resolver.java View source code |
private Prebuilt resolveLib(Artifact artifact, Path project) throws ArtifactResolutionException, IOException {
Artifact jar = new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), "jar", artifact.getVersion());
Path relativePath = resolveArtifact(jar, project);
Prebuilt library = new Prebuilt(jar.getArtifactId(), jar.toString(), relativePath);
downloadSources(jar, project, library);
return library;
}Example 61
| Project: elpaaso-core-master File: MvnRepoDaoImpl.java View source code |
private Artifact convertToArtifact(MavenReference mavenReference) {
MavenReference mavenReferenceEmpty = mavenReference.duplicateWithEmpty();
Artifact artifact = new DefaultArtifact(mavenReferenceEmpty.getGroupId(), mavenReferenceEmpty.getArtifactId(), mavenReferenceEmpty.getClassifier(), mavenReferenceEmpty.getExtension(), mavenReferenceEmpty.getVersion());
return artifact;
}Example 62
| Project: entando-components-master File: ArtifactInstallerManager.java View source code |
@Override
public List<String> findAvailableVersions(Integer availableComponentId) throws ApsSystemException {
List<String> versionsArray = new ArrayList<String>();
AvailableArtifact availableArtifact = null;
try {
if (null == availableComponentId) {
return null;
}
availableArtifact = this.getComponentCatalogueManager().getArtifact(availableComponentId);
if (null == availableArtifact) {
return null;
}
String entandoVersion = this.getConfigManager().getParam("version");
RepositorySystem system = this.newSystem();
RepositorySystemSession localSession = this.newSession(system);
StringBuilder builder = new StringBuilder();
builder.append(availableArtifact.getGroupId()).append(":").append(availableArtifact.getArtifactId());
builder.append(":[").append(entandoVersion).append(",)");
Artifact artifact = new DefaultArtifact(builder.toString());
VersionRangeRequest rangeRequest = new VersionRangeRequest();
rangeRequest.setArtifact(artifact);
rangeRequest.setRepositories(this.newRepositories());
VersionRangeResult rangeResult = system.resolveVersionRange(localSession, rangeRequest);
List<Version> versions = rangeResult.getVersions();
for (int i = 0; i < versions.size(); i++) {
Version version = versions.get(i);
String componentVersion = version.toString();
if (componentVersion.startsWith(entandoVersion)) {
versionsArray.add(componentVersion);
}
}
} catch (Throwable t) {
availableArtifact = (null != availableArtifact) ? availableArtifact : new AvailableArtifact();
_logger.error("Error extracting version for component '{}' - '{}'", availableArtifact.getGroupId(), availableArtifact.getArtifactId(), t);
}
return versionsArray;
}Example 63
| Project: iib-maven-plugin-master File: PrepareBarBuildWorkspaceMojo.java View source code |
private ArtifactResult resolveArtifact(String groupId, String artifactId, String extension, String version) throws MojoFailureException {
Artifact artifact;
try {
artifact = new DefaultArtifact(groupId, artifactId, extension, version);
} catch (IllegalArgumentException e) {
throw new MojoFailureException(e.getMessage(), e);
}
ArtifactRequest artifactRequest = new ArtifactRequest();
artifactRequest.setArtifact(artifact);
artifactRequest.setRepositories(remoteRepos);
getLog().debug("Resolving artifact " + artifact + " from " + remoteRepos);
ArtifactResult result;
try {
result = repoSystem.resolveArtifact(repoSession, artifactRequest);
} catch (ArtifactResolutionException e) {
throw new MojoFailureException(e.getMessage(), e);
}
getLog().debug("Resolved artifact " + artifact + " to " + result.getArtifact().getFile() + " from " + result.getRepository());
return result;
}Example 64
| Project: ivy-maven-plugin-master File: IvyMojo.java View source code |
private ArtifactResult convert(ArtifactRequest request, Artifact mvnArtifact) {
Map<String, String> props = new TreeMap<String, String>();
props.put(ArtifactProperties.LANGUAGE, "java");
props.put(ArtifactProperties.TYPE, mvnArtifact.getType());
props.put(ArtifactProperties.CONSTITUTES_BUILD_PATH, "true");
props.put(ArtifactProperties.INCLUDES_DEPENDENCIES, "false");
return new ArtifactResult(request).setArtifact(new org.eclipse.aether.artifact.DefaultArtifact(mvnArtifact.getGroupId(), mvnArtifact.getArtifactId(), mvnArtifact.getClassifier(), mvnArtifact.getType(), mvnArtifact.getVersion()).setFile(mvnArtifact.getFile()).setProperties(props));
}Example 65
| Project: jmeter-maven-plugin-master File: ConfigureJMeterMojo.java View source code |
private void populateJMeterDirectoryTree() throws DependencyResolutionException, IOException {
if (jmeterArtifacts.isEmpty()) {
throw new DependencyResolutionException("No JMeter dependencies specified!, check jmeterArtifacts and jmeterVersion elements");
}
for (String desiredArtifact : jmeterArtifacts) {
Artifact returnedArtifact = getArtifactResult(new DefaultArtifact(desiredArtifact));
switch(returnedArtifact.getArtifactId()) {
case JMETER_CONFIG_ARTIFACT_NAME:
jmeterConfigArtifact = returnedArtifact;
//TODO Could move the below elsewhere if required.
extractConfigSettings(jmeterConfigArtifact);
break;
case "ApacheJMeter":
runtimeJarName = returnedArtifact.getFile().getName();
copyArtifact(returnedArtifact, workingDirectory);
copyTransitiveRuntimeDependenciesToLibDirectory(returnedArtifact, downloadJMeterDependencies);
break;
default:
copyArtifact(returnedArtifact, libExtDirectory);
copyTransitiveRuntimeDependenciesToLibDirectory(returnedArtifact, downloadJMeterDependencies);
}
}
if (confFilesDirectory.exists()) {
CopyFilesInTestDirectory(confFilesDirectory, new File(jmeterDirectory, "bin"));
}
}Example 66
| Project: monitoring-master File: DependencyResolver.java View source code |
public String getNewestVersion(String groupId, String artifactId) throws VersionRangeResolutionException {
Artifact artifact = new DefaultArtifact(groupId, artifactId, "jar", "[0,)");
VersionRangeRequest rangeRequest = new VersionRangeRequest();
rangeRequest.setArtifact(artifact);
rangeRequest.setRepositories(repositories);
VersionRangeResult rangeResult = system.resolveVersionRange(session, rangeRequest);
Version newestVersion = rangeResult.getHighestVersion();
return newestVersion.toString();
}Example 67
| Project: pinpoint-master File: DependencyResolver.java View source code |
public String getNewestVersion(String groupId, String artifactId) throws VersionRangeResolutionException {
Artifact artifact = new DefaultArtifact(groupId, artifactId, "jar", "[0,)");
VersionRangeRequest rangeRequest = new VersionRangeRequest();
rangeRequest.setArtifact(artifact);
rangeRequest.setRepositories(repositories);
VersionRangeResult rangeResult = system.resolveVersionRange(session, rangeRequest);
Version newestVersion = rangeResult.getHighestVersion();
return newestVersion.toString();
}Example 68
| Project: platform_build-master File: Resolver.java View source code |
private Prebuilt resolveLib(Artifact artifact, Path project) throws ArtifactResolutionException, IOException {
Artifact jar = new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), "jar", artifact.getVersion());
Path relativePath = resolveArtifact(jar, project);
Prebuilt library = new Prebuilt(jar.getArtifactId(), jar.toString(), relativePath);
downloadSources(jar, project, library);
return library;
}Example 69
| Project: Resteasy-master File: MavenUtil.java View source code |
public File createMavenGavFile(String artifactGav) throws MalformedURLException {
Artifact artifact = new DefaultArtifact(artifactGav);
if (artifact.getVersion() == null) {
throw new IllegalArgumentException("Null version");
}
VersionScheme versionScheme = new GenericVersionScheme();
try {
versionScheme.parseVersion(artifact.getVersion());
} catch (InvalidVersionSpecificationException e) {
throw new IllegalArgumentException(e);
}
try {
versionScheme.parseVersionRange(artifact.getVersion());
throw new IllegalArgumentException(artifact.getVersion() + " is a version range. A specific version is needed");
} catch (InvalidVersionSpecificationException expected) {
}
RepositorySystemSession session = newRepositorySystemSession();
ArtifactRequest artifactRequest = new ArtifactRequest();
artifactRequest.setArtifact(artifact);
for (RemoteRepository remoteRepo : remoteRepositories) {
artifactRequest.addRepository(remoteRepo);
}
ArtifactResult artifactResult;
try {
artifactResult = REPOSITORY_SYSTEM.resolveArtifact(session, artifactRequest);
} catch (ArtifactResolutionException e) {
throw new RuntimeException(e);
}
File file = artifactResult.getArtifact().getFile().getAbsoluteFile();
return file;
}Example 70
| Project: takari-lifecycle-master File: AetherUtils.java View source code |
public static org.apache.maven.artifact.Artifact toArtifact(Artifact artifact) {
if (artifact == null) {
return null;
}
ArtifactHandler handler = newHandler(artifact);
/*
* NOTE: From Artifact.hasClassifier(), an empty string and a null both denote "no classifier". However, some plugins only check for null, so be sure to nullify an empty classifier.
*/
org.apache.maven.artifact.Artifact result = new org.apache.maven.artifact.DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), null, artifact.getProperty(ArtifactProperties.TYPE, artifact.getExtension()), nullify(artifact.getClassifier()), handler);
result.setFile(artifact.getFile());
result.setResolved(artifact.getFile() != null);
List<String> trail = new ArrayList<String>(1);
trail.add(result.getId());
result.setDependencyTrail(trail);
return result;
}Example 71
| Project: capsule-maven-plugin-master File: CapsuleMojo.java View source code |
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
// check for type (this overrides custom behaviour)
if (type == Type.empty) {
includeApp = false;
includeAppDep = false;
includePluginDep = false;
includeTransitiveDep = false;
includeCompileDep = false;
includeRuntimeDep = false;
includeProvidedDep = false;
includeSystemDep = false;
includeTestDep = false;
includeOptionalDep = false;
resolveApp = true;
resolveAppDep = true;
resolvePluginDep = true;
resolveTransitiveDep = true;
resolveCompileDep = true;
resolveRuntimeDep = true;
resolveProvidedDep = false;
resolveSystemDep = false;
resolveTestDep = false;
resolveOptionalDep = false;
} else if (type == Type.thin) {
includeApp = true;
includeAppDep = false;
includePluginDep = false;
includeTransitiveDep = false;
includeCompileDep = false;
includeRuntimeDep = false;
includeProvidedDep = false;
includeSystemDep = false;
includeTestDep = false;
includeOptionalDep = false;
resolveApp = false;
resolveAppDep = true;
resolvePluginDep = true;
resolveTransitiveDep = true;
resolveCompileDep = true;
resolveRuntimeDep = true;
resolveProvidedDep = false;
resolveSystemDep = false;
resolveTestDep = false;
resolveOptionalDep = false;
} else if (type == Type.fat) {
includeApp = true;
includeAppDep = true;
includePluginDep = true;
includeTransitiveDep = true;
includeCompileDep = true;
includeRuntimeDep = true;
includeProvidedDep = false;
includeSystemDep = false;
includeTestDep = false;
includeOptionalDep = false;
resolveApp = false;
resolveAppDep = false;
resolvePluginDep = false;
resolveTransitiveDep = false;
resolveCompileDep = false;
resolveRuntimeDep = false;
resolveProvidedDep = false;
resolveSystemDep = false;
resolveTestDep = false;
resolveOptionalDep = false;
}
// check for exec plugin
if (execPluginConfig != null && project.getPlugin(EXEC_PLUGIN_KEY) != null) {
final Plugin plugin = project.getPlugin(EXEC_PLUGIN_KEY);
if (execPluginConfig.equals("root")) {
execConfig = (Xpp3Dom) plugin.getConfiguration();
} else {
final List<PluginExecution> executions = plugin.getExecutions();
for (final PluginExecution execution : executions) {
if (execution.getId().equals(execPluginConfig)) {
execConfig = (Xpp3Dom) execution.getConfiguration();
break;
}
}
}
}
// get app class from exec config (but only if app class is not set)
if (appClass == null && execConfig != null) {
final Xpp3Dom mainClassElement = execConfig.getChild("mainClass");
if (mainClassElement != null)
appClass = mainClassElement.getValue();
}
// fail if no app class
if (appClass == null)
throw new MojoFailureException(logPrefix() + " appClass not set (or could not be obtained from the exec plugin mainClass)");
// resolve outputDir name (the file name of the capsule jar)
this.outputName = this.fileName != null ? this.fileName : this.finalName;
if (this.fileDesc != null)
outputName += this.fileDesc;
// check for caplets existence
if (this.caplets == null)
this.caplets = "";
if (!caplets.isEmpty()) {
final StringBuilder capletString = new StringBuilder();
final File classesDir = new File(this.buildDir, "classes");
for (final String caplet : this.caplets.split(" ")) {
try {
Files.walkFileTree(classesDir.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path path, final BasicFileAttributes attrs) {
if (!attrs.isDirectory() && path.toString().contains(caplet)) {
capletFiles.put(caplet, path.toFile());
return FileVisitResult.TERMINATE;
}
return FileVisitResult.CONTINUE;
}
});
} catch (final IOException e) {
e.printStackTrace();
}
if (!capletFiles.containsKey(caplet))
if (!// not from repo
caplet.contains(// not from repo
":"))
warn("Could not find caplet " + caplet + " class, skipping.");
if (capletString.length() > 0)
capletString.append(" ");
capletString.append(caplet);
}
caplets = capletString.toString();
}
// if no capsule ver specified, find the latest one
if (capsuleVersion == null) {
final DefaultArtifact artifact = new DefaultArtifact(CAPSULE_GROUP, "capsule", null, null, "[0,)");
final VersionRangeRequest request = new VersionRangeRequest().setRepositories(remoteRepos).setArtifact(artifact);
try {
final VersionRangeResult result = repoSystem.resolveVersionRange(repoSession, request);
// get the latest version that is not a snapshot
for (int i = result.getVersions().size() - 1; i >= 0; i--) {
final String currentVersion = result.getVersions().get(i).toString();
if (!currentVersion.contains("SNAPSHOT")) {
capsuleVersion = result.getVersions().get(i).toString();
break;
}
}
} catch (VersionRangeResolutionException e) {
throw new MojoFailureException(e.getMessage());
}
}
// double check outputDir is not in some undesired locations
final List<String> illegalOutputPaths = Arrays.asList(this.buildDir.getPath() + File.separatorChar + "classes", this.buildDir.getPath() + File.separatorChar + "classes/");
if (illegalOutputPaths.contains(this.outputDir.getPath())) {
this.outputDir = this.buildDir;
debug("Output was an illegal path, resorting to default build directory.");
}
// build path if doesn't exist
if (!outputDir.exists()) {
boolean success = outputDir.mkdirs();
if (!success)
throw new MojoFailureException("Failed to build outputDir path");
}
info("[Capsule Version]: " + capsuleVersion);
info("[Output Directory]: " + outputDir.toString());
info("[Build Info]: " + buildInfoString());
try {
build();
} catch (final IOException e) {
e.printStackTrace();
throw new MojoFailureException(e.getMessage());
}
}Example 72
| Project: drools-master File: MavenRepository.java View source code |
public List<DependencyDescriptor> getArtifactDependecies(String artifactName) {
Artifact artifact = new DefaultArtifact(artifactName);
CollectRequest collectRequest = new CollectRequest();
Dependency root = new Dependency(artifact, "");
collectRequest.setRoot(root);
for (RemoteRepository repo : remoteRepositoriesForRequest) {
collectRequest.addRepository(repo);
}
CollectResult collectResult;
try {
collectResult = aether.getSystem().collectDependencies(aether.getSession(), collectRequest);
} catch (DependencyCollectionException e) {
throw new RuntimeException(e);
}
CollectDependencyVisitor visitor = new CollectDependencyVisitor();
collectResult.getRoot().accept(visitor);
List<DependencyDescriptor> descriptors = new ArrayList<DependencyDescriptor>();
for (DependencyNode node : visitor.getDependencies()) {
// skip root to not add artifact as dependency
if (node.getDependency().equals(root)) {
continue;
}
descriptors.add(new DependencyDescriptor(node.getDependency().getArtifact()));
}
return descriptors;
}Example 73
| Project: eosgi-maven-plugin-master File: DistMojo.java View source code |
private Artifact resolveDistPackage(final String frameworkArtifact) throws MojoExecutionException {
String[] distPackageIdParts;
try {
distPackageIdParts = resolveDistPackageId(frameworkArtifact);
} catch (IOException e) {
throw new MojoExecutionException("Could not get distribution package", e);
}
ArtifactRequest artifactRequest = new ArtifactRequest();
artifactRequest.setArtifact(new DefaultArtifact(distPackageIdParts[0], distPackageIdParts[1], "zip", distPackageIdParts[2]));
return artifactResolver.resolve(artifactRequest);
}Example 74
| Project: Illarion-Java-master File: MavenDownloader.java View source code |
/**
* Download the artifacts. This will check if the files are present and download all missing files.
*
* @param groupId the group id of the artifact to download
* @param artifactId the artifact id of the artifact to download
* @param callback the callback implementation to report to
* @return the files that have to be in the classpath to run the application
*/
@Nullable
public Collection<File> downloadArtifact(@Nonnull String groupId, @Nonnull String artifactId, @Nonnull MavenDownloaderCallback callback) throws DependencyCollectionException, InterruptedException, ExecutionException {
Artifact artifact = new DefaultArtifact(groupId, artifactId, "jar", "[1,]");
try {
callback.reportNewState(State.SearchingNewVersion, null, offline, null);
VersionRangeRequest request = new VersionRangeRequest();
request.setArtifact(artifact);
request.setRepositories(Collections.singletonList(illarionRepository));
request.setRequestContext(RUNTIME);
VersionRangeResult result = system.resolveVersionRange(session, request);
NavigableSet<String> versions = new TreeSet<>(new MavenVersionComparator());
result.getVersions().stream().filter( version -> snapshot || !version.toString().contains("SNAPSHOT")).forEach( version -> {
log.info("Found {}:{}:jar:{}", groupId, artifactId, version);
versions.add(version.toString());
});
if (!versions.isEmpty()) {
artifact = new DefaultArtifact(groupId, artifactId, "jar", versions.pollLast());
}
} catch (VersionRangeResolutionException ignored) {
}
callback.reportNewState(ResolvingDependencies, null, offline, null);
repositoryListener.setCallback(callback);
repositoryListener.setOffline(offline);
Dependency dependency = new Dependency(artifact, RUNTIME, false);
List<String> usedScopes = Arrays.asList(COMPILE, RUNTIME, SYSTEM);
DependencySelector selector = new AndDependencySelector(new OptionalDependencySelector(), new ScopeDependencySelector(usedScopes, null));
session.setDependencySelector(selector.deriveChildSelector(new DefaultDependencyCollectionContext(session, dependency)));
DependencyFilter filter = DependencyFilterUtils.classpathFilter(RUNTIME, COMPILE);
try {
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot(dependency);
collectRequest.setRepositories(repositories);
CollectResult collectResult = system.collectDependencies(session, collectRequest);
ProgressMonitor progressMonitor = new ProgressMonitor();
ArtifactRequestTracer tracer = new DefaultArtifactRequestTracer(offline, callback, progressMonitor);
ArtifactRequestBuilder builder = new ArtifactRequestBuilder(system, session, tracer);
DependencyVisitor visitor = new FilteringDependencyVisitor(builder, filter);
visitor = new TreeDependencyVisitor(visitor);
collectResult.getRoot().accept(visitor);
List<FutureArtifactRequest> requests = builder.getRequests();
for (@Nonnull FutureArtifactRequest request : requests) {
progressMonitor.addChild(request.getProgressMonitor());
}
callback.reportNewState(ResolvingArtifacts, progressMonitor, offline, null);
ExecutorService executorService = Executors.newFixedThreadPool(4, new ThreadFactoryBuilder().setDaemon(false).setNameFormat("Download Thread-%d").build());
List<Future<ArtifactResult>> results = executorService.invokeAll(requests);
executorService.shutdown();
while (!executorService.awaitTermination(1, TimeUnit.MINUTES)) {
log.info("Downloading is not done yet.");
}
Collection<File> result = new ArrayList<>();
for (@Nonnull Future<ArtifactResult> artifactResult : results) {
result.add(artifactResult.get().getArtifact().getFile());
}
if (result.isEmpty()) {
callback.resolvingDone(Collections.<File>emptyList());
return null;
}
callback.resolvingDone(result);
return result;
} catch (@Nonnull DependencyCollectionExceptionInterruptedException | ExecutionException | e) {
callback.resolvingFailed(e);
throw e;
}
}Example 75
| Project: license-check-master File: OpenSourceLicenseCheckMojo.java View source code |
/**
* Uses Aether to retrieve an artifact from the repository.
*
* @param coordinates as in groupId:artifactId:version
* @return the located artifact
*/
Artifact retrieveArtifact(final String coordinates) {
final ArtifactRequest request = new ArtifactRequest();
request.setArtifact(new DefaultArtifact(coordinates));
request.setRepositories(remoteRepos);
ArtifactResult result = null;
try {
result = repoSystem.resolveArtifact(repoSession, request);
} catch (final ArtifactResolutionException e) {
getLog().error("Could not resolve parent artifact (" + coordinates + "): " + e.getMessage());
}
if (result != null) {
return RepositoryUtils.toArtifact(result.getArtifact());
}
return null;
}Example 76
| Project: wildfly-core-master File: MavenUtil.java View source code |
URL createMavenGavURL(String artifactGav) throws MalformedURLException {
Artifact artifact = new DefaultArtifact(artifactGav);
if (artifact.getVersion() == null) {
throw new IllegalArgumentException("Null version");
}
VersionScheme versionScheme = new GenericVersionScheme();
try {
versionScheme.parseVersion(artifact.getVersion());
} catch (InvalidVersionSpecificationException e) {
throw new IllegalArgumentException(e);
}
try {
versionScheme.parseVersionRange(artifact.getVersion());
throw new IllegalArgumentException(artifact.getVersion() + " is a version range. A specific version is needed");
} catch (InvalidVersionSpecificationException expected) {
}
RepositorySystemSession session = newRepositorySystemSession();
ArtifactRequest artifactRequest = new ArtifactRequest();
artifactRequest.setArtifact(artifact);
for (RemoteRepository remoteRepo : remoteRepositories) {
artifactRequest.addRepository(remoteRepo);
}
ArtifactResult artifactResult;
try {
artifactResult = REPOSITORY_SYSTEM.resolveArtifact(session, artifactRequest);
} catch (ArtifactResolutionException e) {
throw new RuntimeException(e);
}
File file = artifactResult.getArtifact().getFile().getAbsoluteFile();
return file.toURI().toURL();
}Example 77
| Project: capsule-maven-master File: DependencyManager.java View source code |
private Dependency clean(Dependency d) {
// necessary for dependency equality
// SNAPSHOT dependencies get resolved to specific artifacts, so returned dependency is different from original
final Artifact a = d.getArtifact();
return new Dependency(new DefaultArtifact(a.getGroupId(), a.getArtifactId(), a.getClassifier(), a.getExtension(), a.getBaseVersion()), d.getScope(), d.getOptional(), d.getExclusions());
}Example 78
| Project: grails-maven-master File: AbstractGrailsMojo.java View source code |
protected Collection<File> resolveArtifactIds(Collection<String> artifactIds) throws MojoExecutionException {
Collection<ArtifactRequest> requests = new ArrayList<ArtifactRequest>();
for (String artifactId : artifactIds) {
ArtifactRequest request = new ArtifactRequest();
request.setArtifact(new DefaultArtifact(artifactId));
request.setRepositories(remoteRepos);
getLog().debug("Resolving artifact " + artifactId + " from " + remoteRepos);
requests.add(request);
}
Collection<File> files = new ArrayList<File>();
try {
List<ArtifactResult> result = repoSystem.resolveArtifacts(repoSession, requests);
for (ArtifactResult artifactResult : result) {
File file = artifactResult.getArtifact().getFile();
files.add(file);
getLog().debug("Resolved artifact " + artifactResult.getArtifact().getArtifactId() + " to " + file + " from " + artifactResult.getRepository());
}
} catch (ArtifactResolutionException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
return files;
}Example 79
| Project: maven-native-plugin-master File: AbstractDependencyMojo.java View source code |
/**
* Gets the project's full dependency tree prior to dependency mediation. This is required if
* we want to know where to push libraries in the linker line.
* @return {@link org.eclipse.aether.graph.DependencyNode Root node} of the projects verbose dependency tree.
* @since 3.5.2
*/
protected org.eclipse.aether.graph.DependencyNode getVerboseDependencyTree() {
// Create CollectRequest object that will be submitted to collect the dependencies
CollectRequest collectReq = new CollectRequest();
// Get artifact this Maven project is attempting to build
Artifact art = getMavenProject().getArtifact();
DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(repoSession);
// Set the No-Op Graph transformer so tree stays intact
session.setDependencyGraphTransformer(new NoopDependencyGraphTransformer());
// Create Aether graph dependency object from params extracted above
org.eclipse.aether.graph.Dependency dep = new org.eclipse.aether.graph.Dependency(new org.eclipse.aether.artifact.DefaultArtifact(art.getGroupId(), art.getArtifactId(), null, art.getVersion()), null);
// Set the root of the request, in this case the current project will be the root
collectReq.setRoot(dep);
// Set the repos the collectReq will hit
collectReq.setRepositories(projectRepos);
try {
return repoSystem.collectDependencies(session, collectReq).getRoot();
} catch (DependencyCollectionException exception) {
this.getLog().warn("Could not collect dependencies from repo system", exception);
return null;
}
}Example 80
| Project: nar-maven-plugin-master File: AbstractDependencyMojo.java View source code |
/**
* Gets the project's full dependency tree prior to dependency mediation. This is required if
* we want to know where to push libraries in the linker line.
* @return {@link org.eclipse.aether.graph.DependencyNode Root node} of the projects verbose dependency tree.
* @since 3.5.2
*/
protected org.eclipse.aether.graph.DependencyNode getVerboseDependencyTree() {
// Create CollectRequest object that will be submitted to collect the dependencies
CollectRequest collectReq = new CollectRequest();
// Get artifact this Maven project is attempting to build
Artifact art = getMavenProject().getArtifact();
DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(repoSession);
// Set the No-Op Graph transformer so tree stays intact
session.setDependencyGraphTransformer(new NoopDependencyGraphTransformer());
// Create Aether graph dependency object from params extracted above
org.eclipse.aether.graph.Dependency dep = new org.eclipse.aether.graph.Dependency(new org.eclipse.aether.artifact.DefaultArtifact(art.getGroupId(), art.getArtifactId(), null, art.getVersion()), null);
// Set the root of the request, in this case the current project will be the root
collectReq.setRoot(dep);
// Set the repos the collectReq will hit
collectReq.setRepositories(projectRepos);
try {
return repoSystem.collectDependencies(session, collectReq).getRoot();
} catch (DependencyCollectionException exception) {
this.getLog().warn("Could not collect dependencies from repo system", exception);
return null;
}
}Example 81
| Project: afc-master File: AbstractArakhneMojo.java View source code |
/**
* Create an artifact from the given values.
*
* @param groupId group id.
* @param artifactId artifact id.
* @param version version number.
* @param scope artifact scope.
* @param type artifact type.
* @return the artifact
*/
public final Artifact createArtifact(String groupId, String artifactId, String version, String scope, String type) {
VersionRange versionRange = null;
if (version != null) {
versionRange = VersionRange.createFromVersion(version);
}
String desiredScope = scope;
if (Artifact.SCOPE_TEST.equals(desiredScope)) {
desiredScope = Artifact.SCOPE_TEST;
}
if (Artifact.SCOPE_PROVIDED.equals(desiredScope)) {
desiredScope = Artifact.SCOPE_PROVIDED;
}
if (Artifact.SCOPE_SYSTEM.equals(desiredScope)) {
// system scopes come through unchanged...
desiredScope = Artifact.SCOPE_SYSTEM;
}
final ArtifactHandler handler = getArtifactHandlerManager().getArtifactHandler(type);
return new org.apache.maven.artifact.DefaultArtifact(groupId, artifactId, versionRange, desiredScope, type, null, handler, false);
}Example 82
| Project: phantomjs-maven-plugin-master File: ArtifactBuilder.java View source code |
public Artifact createArtifact(String groupId, String artifactId, Archive archive) {
return new DefaultArtifact(groupId, artifactId, archive.getClassifier(), archive.getExtension(), archive.getVersion());
}Example 83
| Project: sling-master File: AetherSetup.java View source code |
public File download(String coordinates) throws ArtifactResolutionException {
ArtifactResult fromResult = system.resolveArtifact(session, new ArtifactRequest(new DefaultArtifact(coordinates), repos, null));
return fromResult.getArtifact().getFile();
}Example 84
| Project: soapui-junit-mockrunner-master File: SoapUI.java View source code |
/**
* Will create the soapui artifact that is required to run soapui mocks.
*
* @param version
* the specific version of soapui, if null it will just use
* default {@link #version()}
*
* @return soapui artifact descriptor
*/
public static final Artifact newSoapUIArtifact(String version) {
return new DefaultArtifact("com.smartbear.soapui", "soapui", "jar", (version != null ? version : version()));
}Example 85
| Project: activemq-artemis-master File: ArtemisAbstractPlugin.java View source code |
protected Artifact newArtifact(String artifactID) throws MojoFailureException {
Artifact artifact;
try {
artifact = new DefaultArtifact(artifactID);
} catch (IllegalArgumentException e) {
throw new MojoFailureException(e.getMessage(), e);
}
return artifact;
}Example 86
| Project: SmallMind-master File: MavenRepository.java View source code |
public Artifact acquireArtifact(DefaultRepositorySystemSession session, MavenCoordinate mavenCoordinate) throws ArtifactResolutionException {
return acquireArtifact(session, new DefaultArtifact(mavenCoordinate.getGroupId(), mavenCoordinate.getArtifactId(), mavenCoordinate.getClassifier(), mavenCoordinate.getExtension(), mavenCoordinate.getVersion()));
}Example 87
| Project: Clay-master File: Aether.java View source code |
/**
* Other way to run {@link #resolve(org.eclipse.aether.artifact.Artifact)}
*
* @param artifactCoordinates The artifact coordinates in the format
* {@code <groupId>:<artifactId>[:<extension>[:<classifier>]]:<version>}, must not be {@code null}.
*/
public AetherResult resolve(String artifactCoordinates) throws AetherException {
return resolve(new DefaultArtifact(artifactCoordinates));
}