下面列出了org.apache.maven.plugin.BuildPluginManager#org.apache.maven.repository.RepositorySystem 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void setUpProject(File pomFile, AbstractMojo mojo) throws Exception {
super.setUp();
MockitoAnnotations.initMocks(this);
ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class);
buildingRequest.setResolveDependencies(true);
when(session.getProjectBuildingRequest()).thenReturn(buildingRequest);
DefaultRepositorySystemSession repositorySession = MavenRepositorySystemUtils.newSession();
repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory()
.newInstance(repositorySession, new LocalRepository(RepositorySystem.defaultUserLocalRepository)));
when(buildingRequest.getRepositorySession()).thenReturn(repositorySession);
ProjectBuilder builder = lookup(ProjectBuilder.class);
ProjectBuildingResult build = builder.build(pomFile, buildingRequest);
MavenProject project = build.getProject();
project.getBuild().setOutputDirectory(new File( "target/test-classes").getAbsolutePath());
setVariableValueToObject(mojo, "project", project);
}
static Stream<String> getPluginRuntimeDependencyEntries(AbstractMojo mojo, MavenProject project, Log log,
RepositorySystem repositorySystem, ArtifactRepository localRepository,
List<ArtifactRepository> remoteRepositories) {
PluginDescriptor pluginDescriptor = (PluginDescriptor) mojo.getPluginContext().get(PLUGIN_DESCRIPTOR);
Plugin plugin = project.getBuild().getPluginsAsMap().get(pluginDescriptor.getPluginLookupKey());
List<ArtifactResolutionResult> artifactResolutionResults = plugin //
.getDependencies() //
.stream() //
.map(repositorySystem::createDependencyArtifact) //
.map(a -> Util.resolve(log, a, repositorySystem, localRepository, remoteRepositories)) //
.collect(Collectors.toList());
Stream<Artifact> originalArtifacts = artifactResolutionResults.stream()
.map(ArtifactResolutionResult::getOriginatingArtifact);
Stream<Artifact> childArtifacts = artifactResolutionResults.stream()
.flatMap(resolutionResult -> resolutionResult.getArtifactResolutionNodes().stream())
.map(ResolutionNode::getArtifact);
return Stream.concat(originalArtifacts, childArtifacts).map(Artifact::getFile).map(File::getAbsolutePath);
}
public @Override List<Archetype> getArchetypes() {
List<Archetype> lst = new ArrayList<Archetype>();
List<NBVersionInfo> archs = RepositoryQueries.findArchetypesResult(Collections.singletonList(RepositoryPreferences.getInstance().getLocalRepository())).getResults();
if (archs == null) {
return lst;
}
for (NBVersionInfo art : archs) {
Archetype arch = new Archetype(!"maven-archetype".equalsIgnoreCase(art.getPackaging())); //NOI18N
arch.setArtifactId(art.getArtifactId());
arch.setGroupId(art.getGroupId());
arch.setVersion(art.getVersion());
arch.setName(art.getProjectName());
arch.setDescription(art.getProjectDescription());
arch.setRepository(RepositorySystem.DEFAULT_LOCAL_REPO_ID);
lst.add(arch);
}
return lst;
}
private void checkCentral() {
String sel = (String)comMirrorOf.getSelectedItem();
urlmodel.removeAllElements();
if (RepositorySystem.DEFAULT_REMOTE_REPO_ID.equals(sel)) {
//see http://docs.codehaus.org/display/MAVENUSER/Mirrors+Repositories
// for a list of central mirrors.
//TODO might be worth to externalize somehow.
urlmodel.addElement("http://mirrors.ibiblio.org/pub/mirrors/maven2"); //NOI18N
urlmodel.addElement("http://www.ibiblio.net/pub/packages/maven2");//NOI18N
urlmodel.addElement("http://ftp.cica.es/mirrors/maven2");//NOI18N
urlmodel.addElement("http://repo1.sonatype.net/maven2");//NOI18N
urlmodel.addElement("http://repo.exist.com/maven2");//NOI18N
urlmodel.addElement("http://mirrors.redv.com/maven2");//NOI18N
urlmodel.addElement("http://mirrors.dotsrc.org/maven2");//NOI18N
}
}
/**
* Read current project dependencies and check if it don't grab incorrect
* artifacts versions which could be in conflict with plugin dependencies.
*
* @param project
* current project
* @param repoSystem
* repository system
* @param localRepo
* local repository
* @param remoteRepos
* remote repositories
*/
static void checkClasspath(final MavenProject project, final RepositorySystem repoSystem,
final ArtifactRepository localRepo, final List<ArtifactRepository> remoteRepos) {
Plugin plugin = project.getPlugin(YangToSourcesMojo.PLUGIN_NAME);
if (plugin == null) {
LOG.warn("{} {} not found, dependencies version check skipped", LOG_PREFIX, YangToSourcesMojo.PLUGIN_NAME);
} else {
Map<Artifact, Collection<Artifact>> pluginDependencies = new HashMap<>();
getPluginTransitiveDependencies(plugin, pluginDependencies, repoSystem, localRepo, remoteRepos);
Set<Artifact> projectDependencies = project.getDependencyArtifacts();
for (Map.Entry<Artifact, Collection<Artifact>> entry : pluginDependencies.entrySet()) {
checkArtifact(entry.getKey(), projectDependencies);
for (Artifact dependency : entry.getValue()) {
checkArtifact(dependency, projectDependencies);
}
}
}
}
/**
* Read transitive dependencies of given plugin and store them in map.
*
* @param plugin
* plugin to read
* @param map
* map, where founded transitive dependencies will be stored
* @param repoSystem
* repository system
* @param localRepository
* local repository
* @param remoteRepos
* list of remote repositories
*/
private static void getPluginTransitiveDependencies(final Plugin plugin,
final Map<Artifact, Collection<Artifact>> map, final RepositorySystem repoSystem,
final ArtifactRepository localRepository, final List<ArtifactRepository> remoteRepos) {
List<Dependency> pluginDependencies = plugin.getDependencies();
for (Dependency dep : pluginDependencies) {
Artifact artifact = repoSystem.createDependencyArtifact(dep);
ArtifactResolutionRequest request = new ArtifactResolutionRequest();
request.setArtifact(artifact);
request.setResolveTransitively(true);
request.setLocalRepository(localRepository);
request.setRemoteRepositories(remoteRepos);
ArtifactResolutionResult result = repoSystem.resolve(request);
Set<Artifact> pluginDependencyDependencies = result.getArtifacts();
map.put(artifact, pluginDependencyDependencies);
}
}
@Test
public void testExtractAnnotationProcessors() {
final RepositorySystem repository = mock(RepositorySystem.class);
final Plugin plugin = mock(Plugin.class);
when(plugin.getGroupId()).thenReturn("org.apache.maven.plugins");
when(plugin.getArtifactId()).thenReturn("maven-compiler-plugin");
when(plugin.getVersion()).thenReturn("3.8.1");
when(plugin.getConfiguration()).thenReturn(createConfiguration());
when(repository.createArtifact(anyString(), anyString(), anyString(), anyString())).thenAnswer(invocation -> {
final Artifact artifact = mock(Artifact.class);
when(artifact.getGroupId()).thenReturn(invocation.getArgument(0));
when(artifact.getArtifactId()).thenReturn(invocation.getArgument(1));
when(artifact.getVersion()).thenReturn(invocation.getArgument(2));
return artifact;
});
final Set<Artifact> result = extractAnnotationProcessors(repository, plugin);
assertEquals(result.size(), 1);
final Artifact resultElement = result.iterator().next();
assertEquals(resultElement.getGroupId(), "myGroupId");
assertEquals(resultElement.getArtifactId(), "myArtifactId");
assertEquals(resultElement.getVersion(), "1.2.3");
}
@Test
public void testResolveProjectArtifactsEmpty() throws MojoExecutionException {
final RepositorySystem repositorySystem = mock(RepositorySystem.class);
final MavenSession session = mock(MavenSession.class);
final ProjectBuildingRequest projectBuildingRequest = mock(ProjectBuildingRequest.class);
when(session.getProjectBuildingRequest()).thenReturn(projectBuildingRequest);
final ArtifactRepository localRepository = mock(ArtifactRepository.class);
when(projectBuildingRequest.getLocalRepository()).thenReturn(localRepository);
final List<ArtifactRepository> remoteRepositories = emptyList();
when(projectBuildingRequest.getRemoteRepositories()).thenReturn(remoteRepositories);
final ArtifactResolver resolver = new ArtifactResolver(repositorySystem, localRepository, remoteRepositories);
final MavenProject project = mock(MavenProject.class);
final Configuration config = new Configuration(new CompositeSkipper(emptyList()),
new CompositeSkipper(emptyList()), false, false, false, false);
final Set<Artifact> resolved = resolver.resolveProjectArtifacts(project, config);
assertEquals(emptySet(), resolved);
}
static ArtifactResolutionResult resolve(Log log, Artifact artifact, RepositorySystem repositorySystem,
ArtifactRepository localRepository, List<ArtifactRepository> remoteRepositories) {
ArtifactResolutionRequest request = new ArtifactResolutionRequest() //
.setArtifact(artifact) //
.setLocalRepository(localRepository) //
.setRemoteRepositories(remoteRepositories) //
.setResolveTransitively(true) //
.addListener(Util.createLoggingResolutionListener(log));
return repositorySystem.resolve(request);
}
/**
*
* @param mdl
* @param url of the repository
* @param add true == add to model, will not add if the repo is in project but not in model (eg. central repo)
* @return null if repository with given url exists, otherwise a returned newly created item.
*/
public static Repository addModelRepository(MavenProject project, POMModel mdl, String url) {
if (url.contains(RepositorySystem.DEFAULT_REMOTE_REPO_URL) || /* #212336 */url.contains("http://repo1.maven.org/maven2")) {
return null;
}
List<Repository> repos = mdl.getProject().getRepositories();
if (repos != null) {
for (Repository r : repos) {
if (url.equals(r.getUrl())) {
//already in model..either in pom.xml or added in this session.
return null;
}
}
}
List<org.apache.maven.model.Repository> reps = project.getRepositories();
org.apache.maven.model.Repository prjret = null;
Repository ret = null;
if (reps != null) {
for (org.apache.maven.model.Repository re : reps) {
if (url.equals(re.getUrl())) {
prjret = re;
break;
}
}
}
if (prjret == null) {
ret = mdl.getFactory().createRepository();
ret.setUrl(url);
ret.setId(url);
mdl.getProject().addRepository(ret);
}
return ret;
}
/**
* resolve the artifacts associated with the archetype (ideally downloads them to the local repository)
* @param hndl
* @throws ArtifactResolutionException
* @throws ArtifactNotFoundException
*/
public void resolveArtifacts(AggregateProgressHandle hndl) throws ArtifactResolutionException, ArtifactNotFoundException {
MavenEmbedder online = EmbedderFactory.getOnlineEmbedder();
List<ArtifactRepository> repos;
if (getRepository() == null) {
repos = Collections.<ArtifactRepository>singletonList(online.createRemoteRepository(RepositorySystem.DEFAULT_REMOTE_REPO_URL, RepositorySystem.DEFAULT_REMOTE_REPO_ID));
} else {
repos = Collections.<ArtifactRepository>singletonList(online.createRemoteRepository(getRepository(), "custom-repo"));//NOI18N
for (RepositoryInfo info : RepositoryPreferences.getInstance().getRepositoryInfos()) {
if (getRepository().equals(info.getRepositoryUrl())) {
repos = Collections.<ArtifactRepository>singletonList(online.createRemoteRepository(getRepository(), info.getId()));//NOI18N
break;
}
}
}
try {
ProgressTransferListener.setAggregateHandle(hndl);
hndl.start();
//TODO how to rewrite to track progress?
// try {
// WagonManager wagon = online.getPlexusContainer().lookup(WagonManager.class);
// wagon.setDownloadMonitor(new ProgressTransferListener());
// } catch (ComponentLookupException ex) {
// Exceptions.printStackTrace(ex);
// }
online.resolve(getPomArtifact(), repos, online.getLocalRepository());
online.resolve(getArtifact(), repos, online.getLocalRepository());
} catch (ThreadDeath d) { // download interrupted
} catch (IllegalStateException ise) { //download interrupted in dependent thread. #213812
if (!(ise.getCause() instanceof ThreadDeath)) {
throw ise;
}
} finally {
ProgressTransferListener.clearAggregateHandle();
hndl.finish();
}
}
@Override public List<Archetype> getArchetypes() {
List<Archetype> lst = new ArrayList<Archetype>();
List<RepositoryInfo> infos = RepositoryPreferences.getInstance().getRepositoryInfos();
for (RepositoryInfo info : infos) {
if (RepositorySystem.DEFAULT_LOCAL_REPO_ID.equals(info.getId())) {
continue;
}
search(info, lst);
}
return lst;
}
MavenEmbedder(EmbedderConfiguration configuration) throws ComponentLookupException {
embedderConfiguration = configuration;
plexus = configuration.getContainer();
this.maven = (DefaultMaven) plexus.lookup(Maven.class);
this.projectBuilder = plexus.lookup(ProjectBuilder.class);
this.repositorySystem = plexus.lookup(RepositorySystem.class);
this.settingsBuilder = plexus.lookup(SettingsBuilder.class);
this.populator = plexus.lookup(MavenExecutionRequestPopulator.class);
settingsDecrypter = plexus.lookup(SettingsDecrypter.class);
}
protected @Override URLConnection openConnection(URL u) throws IOException {
String path = u.getPath();
if (!path.startsWith("/")) {
throw new IOException(path);
}
String stuff = path.substring(1);
MavenEmbedder online = EmbedderFactory.getOnlineEmbedder();
Artifact a;
String[] pieces = stuff.split(":");
if (pieces.length == 4) {
a = online.createArtifact(pieces[0], pieces[1], pieces[2], pieces[3]);
} else if (pieces.length == 5) {
a = online.createArtifactWithClassifier(pieces[0], pieces[1], pieces[2], pieces[3], pieces[4]);
} else {
throw new IOException(stuff);
}
try {
online.resolve(a, Collections.<ArtifactRepository>singletonList(online.createRemoteRepository(RepositorySystem.DEFAULT_REMOTE_REPO_URL, RepositorySystem.DEFAULT_REMOTE_REPO_ID)), online.getLocalRepository());
} catch (Exception x) {
throw new IOException(stuff + ": " + x, x);
}
File f = a.getFile();
if (!f.isFile()) {
throw new IOException("failed to download " + stuff);
}
Logger.getLogger(MavenProtocolHandler.class.getName()).log(Level.FINE, "resolved {0} -> {1}", new Object[] {stuff, f});
return BaseUtilities.toURI(f).toURL().openConnection();
}
@Override
public void addRepository(Repository repository, boolean replace) throws InvalidRepositoryException {
RepositorySystem repositorySystem = embedder.lookupComponent(RepositorySystem.class);
try {
ArtifactRepository repo = repositorySystem.buildArtifactRepository(repository);
if(replace) {
remoteRepositories.remove(repo);
}
remoteRepositories.add(repo);
remoteRepositories = repositorySystem.getEffectiveRepositories( remoteRepositories );
} catch (org.apache.maven.artifact.InvalidRepositoryException ex) {
throw new InvalidRepositoryException(ex.toString(), repository, ex);
}
}
/**
* Tries to download an artifact.
* @param info a version of an artifact
* @return the file in the local repository (might not exist if download failed)
* @throws AbstractArtifactResolutionException currently never?
* @since 1.17
*/
public static File downloadArtifact(NBVersionInfo info) throws Exception {
Artifact a = createArtifact(info);
MavenEmbedder online = EmbedderFactory.getOnlineEmbedder();
List<ArtifactRepository> remotes;
RepositoryInfo repo = RepositoryPreferences.getInstance().getRepositoryInfoById(info.getRepoId());
if (repo != null && repo.isRemoteDownloadable()) {
remotes = Collections.singletonList(online.createRemoteRepository(repo.getRepositoryUrl(), repo.getId()));
} else {
remotes = Collections.singletonList(online.createRemoteRepository(RepositorySystem.DEFAULT_REMOTE_REPO_URL, RepositorySystem.DEFAULT_REMOTE_REPO_ID));
}
online.resolve(a, remotes, online.getLocalRepository());
return a.getFile();
}
private RepositoryPreferences() {
try {
central = new RepositoryInfo(RepositorySystem.DEFAULT_REMOTE_REPO_ID, /* XXX pull display name from superpom? */RepositorySystem.DEFAULT_REMOTE_REPO_ID, null, RepositorySystem.DEFAULT_REMOTE_REPO_URL);
//this repository can be mirrored
central.setMirrorStrategy(RepositoryInfo.MirrorStrategy.ALL);
} catch (URISyntaxException x) {
throw new AssertionError(x);
}
}
/** @since 2.2 */
@Messages("local=Local")
public @NonNull synchronized RepositoryInfo getLocalRepository() {
if (local == null) {
try {
//TODO do we care about changing the instance when localrepo location changes?
local = new RepositoryInfo(RepositorySystem.DEFAULT_LOCAL_REPO_ID, Bundle.local(), EmbedderFactory.getProjectEmbedder().getLocalRepositoryFile().getAbsolutePath(), null);
local.setMirrorStrategy(RepositoryInfo.MirrorStrategy.NONE);
} catch (URISyntaxException x) {
throw new AssertionError(x);
}
}
return local;
}
@Test
public void checkClasspathTest() throws Exception {
final MavenProject project = mock(MavenProject.class);
final Plugin plugin = mock(Plugin.class);
final RepositorySystem repoSystem = mock(RepositorySystem.class);
final ArtifactRepository localRepo = mock(ArtifactRepository.class);
final ArtifactResolutionResult artifactResolResult = mock(ArtifactResolutionResult.class);
final Artifact artifact = mock(Artifact.class);
final Dependency dep = mock(Dependency.class);
final List<ArtifactRepository> remoteRepos = new ArrayList<>();
remoteRepos.add(localRepo);
final Set<Artifact> artifacts = new HashSet<>();
artifacts.add(artifact);
final List<Dependency> listDepcy = new ArrayList<>();
listDepcy.add(dep);
when(project.getPlugin(anyString())).thenReturn(plugin);
when(plugin.getDependencies()).thenReturn(listDepcy);
when(artifact.getArtifactId()).thenReturn("artifactId");
when(artifact.getGroupId()).thenReturn("groupId");
when(artifact.getVersion()).thenReturn("SNAPSHOT");
when(repoSystem.createDependencyArtifact(dep)).thenReturn(artifact);
when(repoSystem.resolve(any(ArtifactResolutionRequest.class))).thenReturn(artifactResolResult);
when(artifactResolResult.getArtifacts()).thenReturn(artifacts);
when(project.getDependencyArtifacts()).thenReturn(artifacts);
Util.checkClasspath(project, repoSystem, localRepo, remoteRepos);
assertEquals(1, artifacts.size());
assertEquals(1, remoteRepos.size());
assertEquals(1, listDepcy.size());
}
/**
* Extract annotation processors for maven-compiler-plugin configuration.
*
* @param system maven repository system
* @param plugin maven-compiler-plugin plugin
* @return Returns set of maven artifacts configured as annotation processors.
*/
public static Set<Artifact> extractAnnotationProcessors(RepositorySystem system, Plugin plugin) {
requireNonNull(system);
if (!checkCompilerPlugin(plugin)) {
throw new IllegalArgumentException("Plugin is not '" + GROUPID + ":" + ARTIFACTID + "'.");
}
final Object config = plugin.getConfiguration();
if (config == null) {
return emptySet();
}
if (config instanceof Xpp3Dom) {
return stream(((Xpp3Dom) config).getChildren("annotationProcessorPaths"))
.flatMap(aggregate -> stream(aggregate.getChildren("path")))
.map(processor -> system.createArtifact(
extractChildValue(processor, "groupId"),
extractChildValue(processor, "artifactId"),
extractChildValue(processor, "version"),
PACKAGING))
// A path specification is automatically ignored in maven-compiler-plugin if version is absent,
// therefore there is little use in logging incomplete paths that are filtered out.
.filter(a -> !a.getGroupId().isEmpty())
.filter(a -> !a.getArtifactId().isEmpty())
.filter(a -> !a.getVersion().isEmpty())
.collect(Collectors.toSet());
}
// It is expected that this will never occur due to all Configuration instances of all plugins being provided as
// XML document. If this happens to occur on very old plugin versions, we can safely add the type support and
// simply return an empty set.
throw new UnsupportedOperationException("Please report that an unsupported type of configuration container" +
" was encountered: " + config.getClass());
}
ArtifactResolver(RepositorySystem repositorySystem, ArtifactRepository localRepository,
List<ArtifactRepository> remoteRepositories) {
this.repositorySystem = requireNonNull(repositorySystem);
this.localRepository = requireNonNull(localRepository);
this.remoteRepositories = requireNonNull(remoteRepositories);
this.remoteRepositoriesIgnoreCheckSum = repositoriesIgnoreCheckSum(remoteRepositories);
}
@Test
public void testExtractAnnotationProcessorsIllegalInputs() {
assertThrows(NullPointerException.class, () -> extractAnnotationProcessors(null, null));
final Plugin badPlugin = mock(Plugin.class);
when(badPlugin.getGroupId()).thenReturn("org.my-bad-plugin");
when(badPlugin.getArtifactId()).thenReturn("bad-plugin");
when(badPlugin.getVersion()).thenReturn("1.1.1");
assertThrows(NullPointerException.class, () -> extractAnnotationProcessors(null, badPlugin));
final RepositorySystem repository = mock(RepositorySystem.class);
assertThrows(NullPointerException.class, () -> extractAnnotationProcessors(repository, null));
assertThrows(IllegalArgumentException.class, () -> extractAnnotationProcessors(repository, badPlugin));
}
@Test
public void testExtractAnnotationProcessorsNoConfiguration() {
final RepositorySystem repository = mock(RepositorySystem.class);
final Plugin plugin = mock(Plugin.class);
when(plugin.getGroupId()).thenReturn("org.apache.maven.plugins");
when(plugin.getArtifactId()).thenReturn("maven-compiler-plugin");
when(plugin.getVersion()).thenReturn("3.8.1");
assertEquals(extractAnnotationProcessors(repository, plugin), emptySet());
}
@Test
public void testExtractAnnotationProcessorsUnsupportedConfigurationType() {
final RepositorySystem repository = mock(RepositorySystem.class);
final Plugin plugin = mock(Plugin.class);
when(plugin.getGroupId()).thenReturn("org.apache.maven.plugins");
when(plugin.getArtifactId()).thenReturn("maven-compiler-plugin");
when(plugin.getVersion()).thenReturn("3.8.1");
when(plugin.getConfiguration()).thenReturn("Massive configuration encoded in magic \"Hello World!\" string.");
assertThrows(UnsupportedOperationException.class, () -> extractAnnotationProcessors(repository, plugin));
}
@Test
public void testConstructArtifactResolverWithNull() {
final RepositorySystem repositorySystem = mock(RepositorySystem.class);
final ArtifactRepository localRepository = mock(ArtifactRepository.class);
assertThrows(NullPointerException.class,
() -> new ArtifactResolver(null, null, null));
assertThrows(NullPointerException.class,
() -> new ArtifactResolver(null, localRepository, emptyList()));
assertThrows(NullPointerException.class,
() -> new ArtifactResolver(repositorySystem, null, emptyList()));
assertThrows(NullPointerException.class,
() -> new ArtifactResolver(repositorySystem, localRepository, null));
}
@Test
public void testResolveSignaturesEmpty() throws MojoExecutionException {
final RepositorySystem repositorySystem = mock(RepositorySystem.class);
final MavenSession session = mock(MavenSession.class);
final ProjectBuildingRequest projectBuildingRequest = mock(ProjectBuildingRequest.class);
when(session.getProjectBuildingRequest()).thenReturn(projectBuildingRequest);
final ArtifactRepository localRepository = mock(ArtifactRepository.class);
when(projectBuildingRequest.getLocalRepository()).thenReturn(localRepository);
final List<ArtifactRepository> remoteRepositories = emptyList();
when(projectBuildingRequest.getRemoteRepositories()).thenReturn(remoteRepositories);
final ArtifactResolver resolver = new ArtifactResolver(repositorySystem, localRepository, remoteRepositories);
final Map<Artifact, Artifact> resolvedSignatures = resolver.resolveSignatures(
emptyList(), SignatureRequirement.NONE);
assertEquals(resolvedSignatures.size(), 0);
}
/**
* Creates a new <code>ModuleGenerator</code>.
*
* @param repositorySystem the given <code>RepositorySystem</code> is required to resolve the class path of the
* examined maven projects
* @since 2.0.0
*/
public ModuleGenerator(@Nonnull final RepositorySystem repositorySystem) {
packagingHandlers.put("pom", new PomPackagingHandler());
packagingHandlers.put("war", new WarPackagingHandler());
artifactResolverCache = new SequentialLoadingCache<Artifact, File>(NonNullFunctions.toFunction(new NonNullFunction<Artifact, Optional<File>>() {
@Nonnull
@Override
public Optional<File> apply(@Nonnull Artifact input) {
if (!input.isResolved()) {
ArtifactResolutionRequest request = new ArtifactResolutionRequest();
request.setResolveRoot(true);
request.setResolveTransitively(false);
request.setArtifact(input);
ArtifactResolutionResult artifactResolutionResult = repositorySystem.resolve(request);
if (!artifactResolutionResult.isSuccess()) {
logger.warn(" Failed to resolve [{}]; some analyzers may not work properly.", getVersionedKeyFor(input));
return absent();
}
}
File classPathElement = input.getFile();
if (classPathElement == null) {
logger.warn(" No valid path to [{}] found; some analyzers may not work properly.", getVersionedKeyFor(input));
return absent();
}
return of(classPathElement);
}
}));
}
@Before
public void setUp() throws Exception {
mavenProject = givenMavenProject("project");
repositorySystem = mock(RepositorySystem.class);
disableArtifactResolving();
objectUnderTest = new ModuleGenerator(repositorySystem);
}
@Messages({
"Progress_Download=Downloading Maven dependencies for {0}",
"TIT_Error=Panel loading error.",
"BTN_CLOSE=&Close"
})
@NonNull private Lookup createViewerLookup(final @NullAllowed NBVersionInfo info, final @NonNull Artifact artifact, final @NullAllowed List<ArtifactRepository> fRepos) {
final InstanceContent ic = new InstanceContent();
AbstractLookup lookup = new AbstractLookup(ic);
ic.add(artifact);
if (info != null) {
ic.add(info);
}
final Artifact fArt = artifact;
RP.post(new Runnable() {
@Override
public void run() {
MavenEmbedder embedder = EmbedderFactory.getOnlineEmbedder();
AggregateProgressHandle hndl = AggregateProgressFactory.createHandle(Progress_Download(artifact.getId()),
new ProgressContributor[] {
AggregateProgressFactory.createProgressContributor("zaloha") }, //NOI18N
ProgressTransferListener.cancellable(), null);
ProgressTransferListener.setAggregateHandle(hndl);
hndl.start();
try {
List<ArtifactRepository> repos = new ArrayList<ArtifactRepository>();
if (fRepos != null) {
repos.addAll(fRepos);
}
if (repos.isEmpty()) {
//add central repo
repos.add(embedder.createRemoteRepository(RepositorySystem.DEFAULT_REMOTE_REPO_URL, RepositorySystem.DEFAULT_REMOTE_REPO_ID));
//add repository form info
if (info != null && !RepositorySystem.DEFAULT_REMOTE_REPO_ID.equals(info.getRepoId())) {
RepositoryInfo rinfo = RepositoryPreferences.getInstance().getRepositoryInfoById(info.getRepoId());
if (rinfo != null) {
String url = rinfo.getRepositoryUrl();
if (url != null) {
repos.add(embedder.createRemoteRepository(url, rinfo.getId()));
}
}
}
}
MavenProject mvnprj = readMavenProject(embedder, fArt, repos);
if(mvnprj != null){
DependencyNode root = DependencyTreeFactory.createDependencyTree(mvnprj, embedder, Artifact.SCOPE_TEST);
ic.add(root);
ic.add(mvnprj);
}
} catch (ProjectBuildingException ex) {
ErrorPanel pnl = new ErrorPanel(ex);
DialogDescriptor dd = new DialogDescriptor(pnl, TIT_Error());
JButton close = new JButton();
org.openide.awt.Mnemonics.setLocalizedText(close, BTN_CLOSE());
dd.setOptions(new Object[] { close });
dd.setClosingOptions(new Object[] { close });
DialogDisplayer.getDefault().notify(dd);
ic.add(new MavenProject()); // XXX is this useful for anything?
} catch (ThreadDeath d) { // download interrupted
} catch (IllegalStateException ise) { //download interrupted in dependent thread. #213812
if (!(ise.getCause() instanceof ThreadDeath)) {
throw ise;
}
} finally {
hndl.finish();
ProgressTransferListener.clearAggregateHandle();
}
}
});
Action[] toolbarActions = new Action[] {
new AddAsDependencyAction(fArt),
CommonArtifactActions.createScmCheckoutAction(lookup),
CommonArtifactActions.createLibraryAction(lookup)
};
ic.add(toolbarActions);
return lookup;
}
@Messages({
"RUN_Project_Creation=Project Creation",
"RUN_Maven=Create project"
})
private static void runArchetype(File directory, ProjectInfo vi, Archetype arch, @NullAllowed Map<String,String> additional) throws IOException {
BeanRunConfig config = new BeanRunConfig();
config.setProperty("archetypeGroupId", arch.getGroupId()); //NOI18N
config.setProperty("archetypeArtifactId", arch.getArtifactId()); //NOI18N
config.setProperty("archetypeVersion", arch.getVersion()); //NOI18N
String repo = arch.getRepository();
config.setProperty("archetypeRepository", repo != null ? repo : RepositorySystem.DEFAULT_REMOTE_REPO_URL); //NOI18N
config.setProperty("groupId", vi.groupId); //NOI18N
config.setProperty("artifactId", vi.artifactId); //NOI18N
config.setProperty("version", vi.version); //NOI18N
final String pack = vi.packageName;
if (pack != null && pack.trim().length() > 0) {
config.setProperty("package", pack); //NOI18N
}
config.setProperty("basedir", directory.getAbsolutePath());//NOI18N
Map<String, String> baseprops = new HashMap<String, String>(config.getProperties());
if (additional != null) {
for (Map.Entry<String,String> entry : additional.entrySet()) {
if (baseprops.containsKey(entry.getKey())) {
//don't let the additional props overwrite the values for version, groupId or artifactId
continue;
}
String val = entry.getValue();
//#208146 process the additional prop value through a simplistic extression resolution.
for (Map.Entry<String, String> basePropEnt : baseprops.entrySet()) {
val = val.replace("${" + basePropEnt.getKey() + "}", basePropEnt.getValue());
}
config.setProperty(entry.getKey(), val);
}
}
config.setActivatedProfiles(Collections.<String>emptyList());
config.setExecutionDirectory(directory);
config.setExecutionName(RUN_Project_Creation());
config.setGoals(Collections.singletonList(MavenCommandSettings.getDefault().getCommand(MavenCommandSettings.COMMAND_CREATE_ARCHETYPENG))); //NOI18N
//ExecutionRequest.setInteractive seems to have no influence on archetype plugin.
config.setInteractive(false);
config.setProperty("archetype.interactive", "false");//NOI18N
//#136853 make sure to get the latest snapshot always..
if (arch.getVersion().contains("SNAPSHOT")) { //NOI18N
config.setUpdateSnapshots(true);
}
config.setTaskDisplayName(RUN_Maven());
ExecutorTask task = RunUtils.executeMaven(config); //NOI18N
task.result();
}