use of org.apache.maven.project.ProjectBuildingRequest in project maven-plugins by apache.
the class JavadocReportTest method testProxy.
/**
* Method to test proxy support in the javadoc
*
* @throws Exception if any
*/
public void testProxy() throws Exception {
Settings settings = new Settings();
Proxy proxy = new Proxy();
// dummy proxy
proxy.setActive(true);
proxy.setHost("127.0.0.1");
proxy.setPort(80);
proxy.setProtocol("http");
proxy.setUsername("toto");
proxy.setPassword("toto");
proxy.setNonProxyHosts("www.google.com|*.somewhere.com");
settings.addProxy(proxy);
File testPom = new File(getBasedir(), "src/test/resources/unit/proxy-test/proxy-test-plugin-config.xml");
JavadocReport mojo = lookupMojo(testPom);
MavenSession session = spy(newMavenSession(mojo.project));
ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class);
when(buildingRequest.getRemoteRepositories()).thenReturn(mojo.project.getRemoteArtifactRepositories());
when(session.getProjectBuildingRequest()).thenReturn(buildingRequest);
MavenRepositorySystemSession repositorySession = new MavenRepositorySystemSession();
repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManager(localRepo));
when(buildingRequest.getRepositorySession()).thenReturn(repositorySession);
when(session.getRepositorySession()).thenReturn(repositorySession);
LegacySupport legacySupport = lookup(LegacySupport.class);
legacySupport.setSession(session);
setVariableValueToObject(mojo, "settings", settings);
setVariableValueToObject(mojo, "session", session);
mojo.execute();
File commandLine = new File(getBasedir(), "target/test/unit/proxy-test/target/site/apidocs/javadoc." + (SystemUtils.IS_OS_WINDOWS ? "bat" : "sh"));
assertTrue(FileUtils.fileExists(commandLine.getAbsolutePath()));
String readed = readFile(commandLine);
assertTrue(readed.contains("-J-Dhttp.proxySet=true"));
assertTrue(readed.contains("-J-Dhttp.proxyHost=127.0.0.1"));
assertTrue(readed.contains("-J-Dhttp.proxyPort=80"));
assertTrue(readed.contains("-J-Dhttp.proxyUser=\\\"toto\\\""));
assertTrue(readed.contains("-J-Dhttp.proxyPassword=\\\"toto\\\""));
assertTrue(readed.contains("-J-Dhttp.nonProxyHosts=\\\"www.google.com|*.somewhere.com\\\""));
File options = new File(getBasedir(), "target/test/unit/proxy-test/target/site/apidocs/options");
assertTrue(FileUtils.fileExists(options.getAbsolutePath()));
String optionsContent = readFile(options);
// NO -link expected
assertFalse(optionsContent.contains("-link"));
// real proxy
ProxyServer proxyServer = null;
AuthAsyncProxyServlet proxyServlet;
try {
proxyServlet = new AuthAsyncProxyServlet();
proxyServer = new ProxyServer(proxyServlet);
proxyServer.start();
settings = new Settings();
proxy = new Proxy();
proxy.setActive(true);
proxy.setHost(proxyServer.getHostName());
proxy.setPort(proxyServer.getPort());
proxy.setProtocol("http");
settings.addProxy(proxy);
mojo = lookupMojo(testPom);
setVariableValueToObject(mojo, "settings", settings);
setVariableValueToObject(mojo, "session", session);
mojo.execute();
readed = readFile(commandLine);
assertTrue(readed.contains("-J-Dhttp.proxySet=true"));
assertTrue(readed.contains("-J-Dhttp.proxyHost=" + proxyServer.getHostName()));
assertTrue(readed.contains("-J-Dhttp.proxyPort=" + proxyServer.getPort()));
optionsContent = readFile(options);
// -link expected
// TODO: This got disabled for now!
// This test fails since the last commit but I actually think it only ever worked by accident.
// It did rely on a commons-logging-1.0.4.pom which got resolved by a test which did run previously.
// But after updating to commons-logging.1.1.1 there is no pre-resolved artifact available in
// target/local-repo anymore, thus the javadoc link info cannot get built and the test fails
// I'll for now just disable this line of code, because the test as far as I can see _never_
// did go upstream. The remoteRepository list used is always empty!.
//
// assertTrue( optionsContent.contains( "-link 'http://commons.apache.org/logging/apidocs'" ) );
} finally {
if (proxyServer != null) {
proxyServer.stop();
}
}
// auth proxy
Map<String, String> authentications = new HashMap<>();
authentications.put("foo", "bar");
try {
proxyServlet = new AuthAsyncProxyServlet(authentications);
proxyServer = new ProxyServer(proxyServlet);
proxyServer.start();
settings = new Settings();
proxy = new Proxy();
proxy.setActive(true);
proxy.setHost(proxyServer.getHostName());
proxy.setPort(proxyServer.getPort());
proxy.setProtocol("http");
proxy.setUsername("foo");
proxy.setPassword("bar");
settings.addProxy(proxy);
mojo = lookupMojo(testPom);
setVariableValueToObject(mojo, "settings", settings);
setVariableValueToObject(mojo, "session", session);
mojo.execute();
readed = readFile(commandLine);
assertTrue(readed.contains("-J-Dhttp.proxySet=true"));
assertTrue(readed.contains("-J-Dhttp.proxyHost=" + proxyServer.getHostName()));
assertTrue(readed.contains("-J-Dhttp.proxyPort=" + proxyServer.getPort()));
assertTrue(readed.contains("-J-Dhttp.proxyUser=\\\"foo\\\""));
assertTrue(readed.contains("-J-Dhttp.proxyPassword=\\\"bar\\\""));
optionsContent = readFile(options);
// -link expected
// see comment above (line 829)
// assertTrue( optionsContent.contains( "-link 'http://commons.apache.org/logging/apidocs'" ) );
} finally {
if (proxyServer != null) {
proxyServer.stop();
}
}
}
use of org.apache.maven.project.ProjectBuildingRequest in project maven-plugins by apache.
the class ShadeMojoTest method testShadeWithFilter.
/**
* Tests if a Filter is installed correctly, also if createSourcesJar is set to true.
*
* @throws Exception
*/
public void testShadeWithFilter() throws Exception {
ShadeMojo mojo = new ShadeMojo();
// set createSourcesJar = true
Field createSourcesJar = ShadeMojo.class.getDeclaredField("createSourcesJar");
createSourcesJar.setAccessible(true);
createSourcesJar.set(mojo, Boolean.TRUE);
// configure artifactResolver (mocked) for mojo
ArtifactResolver mockArtifactResolver = new ArtifactResolver() {
@Override
public ArtifactResult resolveArtifact(ProjectBuildingRequest req, final Artifact art) throws ArtifactResolverException {
return new ArtifactResult() {
@Override
public Artifact getArtifact() {
art.setResolved(true);
String fileName = art.getArtifactId() + "-" + art.getVersion() + (art.getClassifier() != null ? "-" + art.getClassifier() : "") + ".jar";
art.setFile(new File(fileName));
return art;
}
};
}
@Override
public ArtifactResult resolveArtifact(ProjectBuildingRequest req, final ArtifactCoordinate coordinate) throws ArtifactResolverException {
return new ArtifactResult() {
@Override
public Artifact getArtifact() {
Artifact art = mock(Artifact.class);
when(art.getGroupId()).thenReturn(coordinate.getGroupId());
when(art.getArtifactId()).thenReturn(coordinate.getArtifactId());
when(art.getType()).thenReturn(coordinate.getExtension());
when(art.getClassifier()).thenReturn(coordinate.getClassifier());
when(art.isResolved()).thenReturn(true);
String fileName = coordinate.getArtifactId() + "-" + coordinate.getVersion() + (coordinate.getClassifier() != null ? "-" + coordinate.getClassifier() : "") + ".jar";
when(art.getFile()).thenReturn(new File(fileName));
return art;
}
};
}
};
Field artifactResolverField = ShadeMojo.class.getDeclaredField("artifactResolver");
artifactResolverField.setAccessible(true);
artifactResolverField.set(mojo, mockArtifactResolver);
// create and configure MavenProject
MavenProject project = new MavenProject();
ArtifactHandler artifactHandler = (ArtifactHandler) lookup(ArtifactHandler.ROLE);
Artifact artifact = new DefaultArtifact("org.apache.myfaces.core", "myfaces-impl", VersionRange.createFromVersion("2.0.1-SNAPSHOT"), "compile", "jar", null, artifactHandler);
// setFile and setResolved
artifact = mockArtifactResolver.resolveArtifact(null, artifact).getArtifact();
project.setArtifact(artifact);
Field projectField = ShadeMojo.class.getDeclaredField("project");
projectField.setAccessible(true);
projectField.set(mojo, project);
// create and configure the ArchiveFilter
ArchiveFilter archiveFilter = new ArchiveFilter();
Field archiveFilterArtifact = ArchiveFilter.class.getDeclaredField("artifact");
archiveFilterArtifact.setAccessible(true);
archiveFilterArtifact.set(archiveFilter, "org.apache.myfaces.core:myfaces-impl");
// add ArchiveFilter to mojo
Field filtersField = ShadeMojo.class.getDeclaredField("filters");
filtersField.setAccessible(true);
filtersField.set(mojo, new ArchiveFilter[] { archiveFilter });
Field sessionField = ShadeMojo.class.getDeclaredField("session");
sessionField.setAccessible(true);
sessionField.set(mojo, mock(MavenSession.class));
// invoke getFilters()
Method getFilters = ShadeMojo.class.getDeclaredMethod("getFilters", new Class[0]);
getFilters.setAccessible(true);
List<Filter> filters = (List<Filter>) getFilters.invoke(mojo);
// assertions - there must be one filter
assertEquals(1, filters.size());
// the filter must be able to filter the binary and the sources jar
Filter filter = filters.get(0);
// binary jar
assertTrue(filter.canFilter(new File("myfaces-impl-2.0.1-SNAPSHOT.jar")));
// sources jar
assertTrue(filter.canFilter(new File("myfaces-impl-2.0.1-SNAPSHOT-sources.jar")));
}
use of org.apache.maven.project.ProjectBuildingRequest in project maven-plugins by apache.
the class DescribeMojo method describePlugin.
/**
* Method for retrieving the plugin description
*
* @param pd contains the plugin description
* @param buffer contains the information to be displayed or printed
* @throws MojoFailureException if any reflection exceptions occur.
* @throws MojoExecutionException if any
*/
private void describePlugin(PluginDescriptor pd, StringBuilder buffer) throws MojoFailureException, MojoExecutionException {
append(buffer, pd.getId(), 0);
buffer.append(LS);
String name = pd.getName();
if (name == null) {
// Can be null because of MPLUGIN-137 (and descriptors generated with maven-plugin-tools-api <= 2.4.3)
ArtifactCoordinate coordinate = toArtifactCoordinate(pd, "jar");
ProjectBuildingRequest pbr = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
pbr.setRemoteRepositories(remoteRepositories);
pbr.setProject(null);
pbr.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
try {
Artifact artifact = artifactResolver.resolveArtifact(pbr, coordinate).getArtifact();
name = projectBuilder.build(artifact, pbr).getProject().getName();
} catch (Exception e) {
// oh well, we tried our best.
getLog().warn("Unable to get the name of the plugin " + pd.getId() + ": " + e.getMessage());
name = pd.getId();
}
}
append(buffer, "Name", name, 0);
appendAsParagraph(buffer, "Description", toDescription(pd.getDescription()), 0);
append(buffer, "Group Id", pd.getGroupId(), 0);
append(buffer, "Artifact Id", pd.getArtifactId(), 0);
append(buffer, "Version", pd.getVersion(), 0);
append(buffer, "Goal Prefix", pd.getGoalPrefix(), 0);
buffer.append(LS);
List<MojoDescriptor> mojos = pd.getMojos();
if (mojos == null) {
append(buffer, "This plugin has no goals.", 0);
return;
}
if ((detail || medium) && !minimal) {
append(buffer, "This plugin has " + mojos.size() + " goal" + (mojos.size() > 1 ? "s" : "") + ":", 0);
buffer.append(LS);
mojos = new ArrayList<MojoDescriptor>(mojos);
PluginUtils.sortMojos(mojos);
for (MojoDescriptor md : mojos) {
if (detail) {
describeMojoGuts(md, buffer, true);
} else {
describeMojoGuts(md, buffer, false);
}
buffer.append(LS);
}
}
if (!detail) {
buffer.append("For more information, run 'mvn help:describe [...] -Ddetail'");
buffer.append(LS);
}
}
use of org.apache.maven.project.ProjectBuildingRequest in project maven-plugins by apache.
the class EvaluateMojo method getArtifactFile.
/**
* @param isPom <code>true</code> to lookup the <code>maven-model</code> artifact jar, <code>false</code> to lookup
* the <code>maven-settings</code> artifact jar.
* @return the <code>org.apache.maven:maven-model|maven-settings</code> artifact jar file for this current
* HelpPlugin pom.
* @throws MojoExecutionException if any
* @throws ProjectBuildingException if any
* @throws ArtifactResolverException if any
*/
private File getArtifactFile(boolean isPom) throws MojoExecutionException, ProjectBuildingException, ArtifactResolverException {
List<Dependency> dependencies = getHelpPluginPom().getDependencies();
for (Dependency depependency : dependencies) {
if (!(depependency.getGroupId().equals("org.apache.maven"))) {
continue;
}
if (isPom) {
if (!(depependency.getArtifactId().equals("maven-model"))) {
continue;
}
} else {
if (!(depependency.getArtifactId().equals("maven-settings"))) {
continue;
}
}
ArtifactCoordinate coordinate = getArtifactCoordinate(depependency.getGroupId(), depependency.getArtifactId(), depependency.getVersion(), "jar");
ProjectBuildingRequest pbr = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
pbr.setRemoteRepositories(remoteRepositories);
return artifactResolver.resolveArtifact(pbr, coordinate).getArtifact().getFile();
}
throw new MojoExecutionException("Unable to find the 'org.apache.maven:" + (isPom ? "maven-model" : "maven-settings") + "' artifact");
}
use of org.apache.maven.project.ProjectBuildingRequest in project maven-plugins by apache.
the class InstallFileMojo method execute.
/**
* @see org.apache.maven.plugin.Mojo#execute()
*/
public void execute() throws MojoExecutionException, MojoFailureException {
if (!file.exists()) {
String message = "The specified file '" + file.getPath() + "' not exists";
getLog().error(message);
throw new MojoFailureException(message);
}
ProjectBuildingRequest buildingRequest = session.getProjectBuildingRequest();
// ----------------------------------------------------------------------
if (localRepositoryPath != null) {
buildingRequest = repositoryManager.setLocalRepositoryBasedir(buildingRequest, localRepositoryPath);
getLog().debug("localRepoPath: " + repositoryManager.getLocalRepositoryBasedir(buildingRequest));
}
File temporaryPom = null;
if (pomFile != null) {
processModel(readModel(pomFile));
} else {
temporaryPom = readingPomFromJarFile();
pomFile = temporaryPom;
}
MavenProject project = createMavenProject();
// We need to set a new ArtifactHandler otherwise
// the extension will be set to the packaging type
// which is sometimes wrong.
DefaultArtifactHandler ah = new DefaultArtifactHandler(packaging);
ah.setExtension(FileUtils.getExtension(file.getName()));
project.getArtifact().setArtifactHandler(ah);
Artifact artifact = project.getArtifact();
if (file.equals(getLocalRepoFile(buildingRequest, artifact))) {
throw new MojoFailureException("Cannot install artifact. " + "Artifact is already in the local repository.\n\nFile in question is: " + file + "\n");
}
if (classifier == null) {
artifact.setFile(file);
if ("pom".equals(packaging)) {
project.setFile(file);
}
} else {
projectHelper.attachArtifact(project, packaging, classifier, file);
}
if (!"pom".equals(packaging)) {
if (pomFile != null) {
if (classifier == null) {
artifact.addMetadata(new ProjectArtifactMetadata(artifact, pomFile));
} else {
project.setFile(pomFile);
}
} else {
temporaryPom = generatePomFile();
ProjectArtifactMetadata pomMetadata = new ProjectArtifactMetadata(artifact, temporaryPom);
if (Boolean.TRUE.equals(generatePom) || (generatePom == null && !getLocalRepoFile(buildingRequest, pomMetadata).exists())) {
getLog().debug("Installing generated POM");
if (classifier == null) {
artifact.addMetadata(pomMetadata);
} else {
project.setFile(temporaryPom);
}
} else if (generatePom == null) {
getLog().debug("Skipping installation of generated POM, already present in local repository");
}
}
}
if (sources != null) {
projectHelper.attachArtifact(project, "jar", "sources", sources);
}
if (javadoc != null) {
projectHelper.attachArtifact(project, "jar", "javadoc", javadoc);
}
try {
// CHECKSTYLE_OFF: LineLength
ProjectInstallerRequest projectInstallerRequest = new ProjectInstallerRequest().setProject(project).setCreateChecksum(createChecksum).setUpdateReleaseInfo(updateReleaseInfo);
// CHECKSTYLE_ON: LineLength
installer.install(buildingRequest, projectInstallerRequest);
} catch (Exception e) {
throw new MojoExecutionException(e.getMessage(), e);
} finally {
if (temporaryPom != null) {
// noinspection ResultOfMethodCallIgnored
temporaryPom.delete();
}
}
}
Aggregations