/** * Installs an artifact to the local repository. The artifact will be installed as type <code>jar * </code>. * * @param model the POM to be installed alongside the artifact * @param jar the artifact to be installed * @throws MojoFailureException if installation fails */ private void installJar(Model model, File jar) throws MojoFailureException { if (!jar.isFile()) throw new MojoFailureException("missing artifact " + jar.getPath()); final File pom; try { pom = File.createTempFile("mcforge", "xml"); } catch (IOException caught) { throw new MojoFailureException("unable to write temporary POM file", caught); } writeModelToFile(model, pom); final InstallRequest request = new InstallRequest(); request.addArtifact( new DefaultArtifact( model.getGroupId(), model.getArtifactId(), null, "pom", model.getVersion(), null, pom)); request.addArtifact( new DefaultArtifact( model.getGroupId(), model.getArtifactId(), null, "jar", model.getVersion(), null, jar)); try { aether.install(aetherSession, request); } catch (InstallationException caught) { throw new MojoFailureException("unable to install artifact " + jar.getName(), caught); } }
/** * Create the fully qualified name of the model (using packaging type "pom"). * * @param model The model. * @return The fully qualified name. */ private String getFullyQualifiedName(Model model) { StringBuilder id = new StringBuilder(); id.append((model.getGroupId() == null) ? "[inherited]" : model.getGroupId()); id.append(":"); id.append(model.getArtifactId()); id.append(":pom:"); id.append((model.getVersion() == null) ? "[inherited]" : model.getVersion()); return id.toString(); }
private String resolveVersion(String modelVersion, Model mavenModel, boolean dependency) { String version = modelVersion; // TODO: download parents and resolve pom.xml properties using aether ? could be pretty // expensive for // the init if (version == null) { if (!dependency) { Parent parent = mavenModel.getParent(); if (parent != null) { version = parent.getVersion(); } } } else if (version.startsWith("$")) { String propertyName = version.substring(2, version.length() - 1); if (propertyName.equals("project.version") || propertyName.equals("pom.version") || propertyName.equals("version")) { version = resolveVersion(mavenModel.getVersion(), mavenModel, false); } else { String value = mavenModel.getProperties().getProperty(propertyName); if (value != null) { version = value; } } } if (version == null) { version = UNKNOWN; } return version; }
MavenProject readProject(File pomFile) throws IOException { MavenXpp3Reader mavenReader = new MavenXpp3Reader(); FileReader fileReader = null; try { fileReader = new FileReader(pomFile); Model model = mavenReader.read(fileReader); model.setPomFile(pomFile); MavenProject project = new MavenProject(model); project.setFile(pomFile); project.setArtifact( createArtifact( pomFile, model.getGroupId(), model.getArtifactId(), model.getVersion(), "compile", model.getPackaging(), "")); return project; } catch (Exception e) { throw new RuntimeException(e); } finally { if (fileReader != null) { fileReader.close(); } } }
@Override public void execute() throws Exception { final File pom = new File(testExecutionDirectory, "pom.xml"); final Model model = getModel(pom); model.setVersion(model.getVersion() + "-SNAPSHOT"); persistModel(pom, model); }
public final void perform() throws Exception { VelocityConfigurator.config(); VelocityContext ctx = new VelocityContext(); try { MavenXpp3Reader reader = new MavenXpp3Reader(); Model model = reader.read(new FileReader("pom.xml")); ctx.put("artifactId", model.getArtifactId()); ctx.put("applicationName", model.getName()); ctx.put("originalPomVersion", model.getVersion()); ctx.put("originalBankaiVersion", model.getProperties().get("version.pt.ist.bankai")); } catch (FileNotFoundException e) { if (requiresMavenProject()) { LOG.error("Could not find pom.xml"); LOG.error("Make sure you're in the project's root folder."); System.exit(-1); } } execute(ctx); }
/** * Compare the list of selected dependencies against the selected targetPOM. If one of the * dependencies is already under dependencyManagement, but has a different version than the * selected dependency, warn the user about this. returns true if the user has been warned (but * this method updates the status itself) * * @param model * @param dependencies */ protected boolean checkDependencies( org.apache.maven.model.Model model, LinkedList<Dependency> dependencies) { if (this.status != null && this.status.getCode() == IStatus.ERROR) { // Don't warn the user if there is already an error return false; } if (model == null || model.getDependencyManagement() == null || model.getDependencyManagement().getDependencies() == null || model.getDependencyManagement().getDependencies().isEmpty()) { return false; } for (Dependency selectedDep : dependencies) { for (org.apache.maven.model.Dependency targetDep : model.getDependencyManagement().getDependencies()) { if (selectedDep.getGroupId().equals(targetDep.getGroupId()) && selectedDep.getArtifactId().equals(targetDep.getArtifactId()) && !selectedDep.getVersion().equals(targetDep.getVersion())) { String modelID = model.getGroupId() + ":" + model.getArtifactId() + ":" + model.getVersion(); // $NON-NLS-1$ //$NON-NLS-2$ if (targetDep.getLocation("") != null && targetDep.getLocation("").getSource() != null) { // $NON-NLS-1$ //$NON-NLS-2$ modelID = targetDep.getLocation("").getSource().getModelId(); // $NON-NLS-1$ } Object[] arguments = { selectedDep.getArtifactId() + "-" + selectedDep.getVersion(), // $NON-NLS-1$ targetDep.getVersion(), modelID }; String message = NLS.bind(Messages.ManageDependenciesDialog_dependencyExistsWarning, arguments); updateStatus(new Status(IStatus.WARNING, MavenEditorPlugin.PLUGIN_ID, message)); return true; } } } return false; }
/** * Create the descriptor and set base information. * * @param model The model. * @param scanner The scanner. * @return The descriptor. */ protected MavenPomDescriptor createMavenPomDescriptor(Model model, Scanner scanner) { ScannerContext context = scanner.getContext(); MavenPomDescriptor pomDescriptor = context.peek(MavenPomDescriptor.class); pomDescriptor.setName(model.getName()); pomDescriptor.setGroupId(model.getGroupId()); pomDescriptor.setArtifactId(model.getArtifactId()); pomDescriptor.setPackaging(model.getPackaging()); pomDescriptor.setVersion(model.getVersion()); String pomFqn = getFullyQualifiedName(model); pomDescriptor.setFullQualifiedName(pomFqn); Coordinates artifactCoordinates = new ModelCoordinates(model); MavenArtifactDescriptor artifact = getArtifactResolver(context).resolve(artifactCoordinates, context); // if the pom describes itself as artifact then the returned artifact // descriptor must be used as pom descriptor (the old instance is // invalidated due to adding labels) if (MavenPomDescriptor.class.isAssignableFrom(artifact.getClass())) { pomDescriptor = MavenPomDescriptor.class.cast(artifact); } pomDescriptor.getDescribes().add(artifact); return pomDescriptor; }
private static ProjectVersionRef modelKey(final Model model) throws ManipulationException { String g = model.getGroupId(); final String a = model.getArtifactId(); String v = model.getVersion(); if (g == null || v == null) { final Parent p = model.getParent(); if (p == null) { throw new ManipulationException( "Invalid model: " + model + " Cannot find groupId and/or version!"); } if (g == null) { g = p.getGroupId(); } if (v == null) { v = p.getVersion(); } } return new ProjectVersionRef(g, a, v); }
/** * @param archetypeVersion * @throws ComponentLookupException * @throws PlexusContainerException */ private void executeCreateArchetype(Model model) throws Exception { log.info("Creating project from Archetype: " + model); String goal = "org.apache.maven.plugins:maven-archetype-plugin:2.2:generate"; Properties properties = new Properties(); properties.put("archetypeGroupId", model.getGroupId()); properties.put("archetypeArtifactId", model.getArtifactId()); properties.put("archetypeVersion", model.getVersion()); properties.put("groupId", "org.jboss.as.quickstarts"); String artifactId = System.currentTimeMillis() + "-" + model.toString().replaceAll("[^a-zA-Z_0-9]", ""); properties.put("artifactId", artifactId); properties.put("version", "0.0.1-SNAPSHOT"); Verifier verifier = new org.apache.maven.it.Verifier(outputDir); verifier.setAutoclean(false); verifier.setSystemProperties(properties); verifier.setLogFileName(artifactId + "-generate.txt"); verifier.executeGoal(goal); log.info("Building project from Archetype: " + model); Verifier buildVerifier = new Verifier(outputDir + File.separator + artifactId); if (onlyMavenCentral) { buildVerifier.addCliOption( "-s " + testOutputDirectory + File.separator + "settings-clear.xml"); } buildVerifier.executeGoal("compile"); // buildVerifier log is inside each project String functionalTestsFolder = outputDir + File.separator + artifactId + File.separator + "functional-tests"; if (new File(functionalTestsFolder).exists()) { log.info("Building functional-tests from: " + functionalTestsFolder); Verifier functionalTestsVerifier = new Verifier(functionalTestsFolder); functionalTestsVerifier.setAutoclean(cleanArchetypes); if (onlyMavenCentral) { functionalTestsVerifier.addCliOption( "-s " + testOutputDirectory + File.separator + "settings-clear.xml"); } functionalTestsVerifier.executeGoal("compile"); } }
public String getVersion() { return pom.getVersion(); }
private DefaultCoreExtension parseMavenPom( URL descriptorUrl, DefaultCoreExtensionRepository repository) throws IOException, XmlPullParserException { DefaultCoreExtension coreExtension = null; InputStream descriptorStream = descriptorUrl.openStream(); try { MavenXpp3Reader reader = new MavenXpp3Reader(); Model mavenModel = reader.read(descriptorStream); String version = resolveVersion(mavenModel.getVersion(), mavenModel, false); String groupId = resolveGroupId(mavenModel.getGroupId(), mavenModel, false); URL extensionURL = getExtensionURL(descriptorUrl); coreExtension = new MavenCoreExtension( repository, extensionURL, new ExtensionId(groupId + ':' + mavenModel.getArtifactId(), version), packagingToType(mavenModel.getPackaging()), mavenModel); coreExtension.setName(mavenModel.getName()); coreExtension.setSummary(mavenModel.getDescription()); for (Developer developer : mavenModel.getDevelopers()) { URL authorURL = null; if (developer.getUrl() != null) { try { authorURL = new URL(developer.getUrl()); } catch (MalformedURLException e) { // TODO: log ? } } coreExtension.addAuthor(new DefaultExtensionAuthor(developer.getId(), authorURL)); } coreExtension.setWebsite(mavenModel.getUrl()); // licenses for (License license : mavenModel.getLicenses()) { coreExtension.addLicense(getExtensionLicense(license)); } // features String featuresString = mavenModel.getProperties().getProperty("xwiki.extension.features"); if (StringUtils.isNotBlank(featuresString)) { coreExtension.setFeatures( this.converter.<Collection<String>>convert(List.class, featuresString)); } // custom properties coreExtension.putProperty("maven.groupId", groupId); coreExtension.putProperty("maven.artifactId", mavenModel.getArtifactId()); // dependencies for (Dependency mavenDependency : mavenModel.getDependencies()) { if (!mavenDependency.isOptional() && (mavenDependency.getScope() == null || mavenDependency.getScope().equals("compile") || mavenDependency.getScope().equals("runtime"))) { String dependencyGroupId = resolveGroupId(mavenDependency.getGroupId(), mavenModel, true); String dependencyArtifactId = mavenDependency.getArtifactId(); String dependencyClassifier = mavenDependency.getClassifier(); String dependencyVersion = resolveVersion(mavenDependency.getVersion(), mavenModel, true); DefaultExtensionDependency extensionDependency = new MavenCoreExtensionDependency( toExtensionId(dependencyGroupId, dependencyArtifactId, dependencyClassifier), new DefaultVersionConstraint(dependencyVersion), mavenDependency); coreExtension.addDependency(extensionDependency); } } } finally { IOUtils.closeQuietly(descriptorStream); } return coreExtension; }
public MojoProjectStub(File projectDir) { this.basedir = projectDir; props.setProperty("basedir", this.basedir.getAbsolutePath()); File pom = new File(getBasedir(), "plugin-config.xml"); MavenXpp3Reader pomReader = new MavenXpp3Reader(); Model model = null; FileReader fileReader = null; try { fileReader = new FileReader(pom); model = pomReader.read(fileReader); setModel(model); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(fileReader); } setGroupId(model.getGroupId()); setArtifactId(model.getArtifactId()); setVersion(model.getVersion()); setName(model.getName()); setUrl(model.getUrl()); setPackaging(model.getPackaging()); setFile(pom); build = model.getBuild(); if (build == null) { build = new Build(); } File srcDir = getStandardDir(getBuild().getSourceDirectory(), "src/main/java"); getBuild().setSourceDirectory(srcDir.getAbsolutePath()); File targetDir = getStandardDir(getBuild().getDirectory(), "target"); getBuild().setDirectory(targetDir.getAbsolutePath()); File outputDir = getStandardDir(getBuild().getOutputDirectory(), "target/classes"); getBuild().setOutputDirectory(outputDir.getAbsolutePath()); List<Resource> resources = new ArrayList<Resource>(); resources.addAll(getBuild().getResources()); if (resources.isEmpty()) { resources = new ArrayList<Resource>(); Resource resource = new Resource(); File resourceDir = normalize("src/main/resources"); resource.setDirectory(resourceDir.getAbsolutePath()); makeDirs(resourceDir); resources.add(resource); } else { // Make this project work on windows ;-) for (Resource resource : resources) { File dir = normalize(resource.getDirectory()); resource.setDirectory(dir.getAbsolutePath()); } } getBuild().setResources(resources); }
/** * Deploys with given Wagon (hint is provided), to deployUrl. It is caller matter to adjust those * two (ie. deployUrl with file: protocol to be deployed with file wagon would be error). Model is * supplied since it is read before. * * @param wagonHint * @param deployUrl * @param model * @throws Exception */ protected void deployArtifacts(File project, String wagonHint, String deployUrl, Model model) throws Exception { log.info( "Deploying project \"" + project.getAbsolutePath() + "\" using Wagon:" + wagonHint + " to URL=\"" + deployUrl + "\"."); // we already check if the pom.xml was in here. File pom = new File(project, "pom.xml"); // FIXME, this needs to be fluffed up a little, should add the classifier, etc. String artifactFileName = model.getArtifactId() + "." + model.getPackaging(); File artifactFile = new File(project, artifactFileName); log.debug("wow, this is working: " + artifactFile.getName()); Gav gav = new Gav( model.getGroupId(), model.getArtifactId(), model.getVersion(), null, model.getPackaging(), 0, new Date().getTime(), model.getName(), false, false, null, false, null); // the Restlet Client does not support multipart forms: // http://restlet.tigris.org/issues/show_bug.cgi?id=71 // int status = DeployUtils.deployUsingPomWithRest( deployUrl, repositoryId, gav, artifactFile, // pom ); if (!"pom".equals(model.getPackaging()) && !artifactFile.isFile()) { throw new FileNotFoundException( "File " + artifactFile.getAbsolutePath() + " doesn't exists!"); } File artifactSha1 = new File(artifactFile.getAbsolutePath() + ".sha1"); File artifactMd5 = new File(artifactFile.getAbsolutePath() + ".md5"); File artifactAsc = new File(artifactFile.getAbsolutePath() + ".asc"); File pomSha1 = new File(pom.getAbsolutePath() + ".sha1"); File pomMd5 = new File(pom.getAbsolutePath() + ".md5"); File pomAsc = new File(pom.getAbsolutePath() + ".asc"); try { if (artifactSha1.exists()) { getDeployUtils() .deployWithWagon( wagonHint, deployUrl, artifactSha1, this.getRelitiveArtifactPath(gav) + ".sha1"); } if (artifactMd5.exists()) { getDeployUtils() .deployWithWagon( wagonHint, deployUrl, artifactMd5, this.getRelitiveArtifactPath(gav) + ".md5"); } if (artifactAsc.exists()) { getDeployUtils() .deployWithWagon( wagonHint, deployUrl, artifactAsc, this.getRelitiveArtifactPath(gav) + ".asc"); } if (artifactFile.exists()) { getDeployUtils() .deployWithWagon(wagonHint, deployUrl, artifactFile, this.getRelitiveArtifactPath(gav)); } if (pomSha1.exists()) { getDeployUtils() .deployWithWagon(wagonHint, deployUrl, pomSha1, this.getRelitivePomPath(gav) + ".sha1"); } if (pomMd5.exists()) { getDeployUtils() .deployWithWagon(wagonHint, deployUrl, pomMd5, this.getRelitivePomPath(gav) + ".md5"); } if (pomAsc.exists()) { getDeployUtils() .deployWithWagon(wagonHint, deployUrl, pomAsc, this.getRelitivePomPath(gav) + ".asc"); } getDeployUtils().deployWithWagon(wagonHint, deployUrl, pom, this.getRelitivePomPath(gav)); } catch (Exception e) { log.error(getTestId() + " Unable to deploy " + artifactFileName, e); throw e; } }
@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); } } } return retval; }
private static String getKey(Model model) { return "project>" + model.getGroupId() + ":" + model.getArtifactId() + ":" + model.getVersion(); }