List of usage examples for org.apache.maven.project MavenProject getProperties
public Properties getProperties()
From source file:com.alibaba.citrus.maven.eclipse.base.eclipse.InstallPluginsMojo.java
License:Open Source License
/** * <p>//from w w w .j a v a2 s . c o m * Install the plugin into the eclipse instance's /plugins directory * </p> * <ol> * <li>Determine whether the plugin should be extracted into a directory or not</li> * <li>If the plugin's target location exists, or overwrite is set to true: * <ol type="a"> * <li>if extract, ensure the plugin target location exists (mkdirs), and extract there.</li> * <li>copy the plugin file from the local repository to the target location</li> * </ol> * <p> * Warn whenever a plugin will overwrite an existing file or directory, and emit an INFO message whenever a plugin * installation is skipped because of an existing file and overwrite == false. * </p> * * @param artifact The plugin dependency as it has been resolved. * @param project The project metadata for the accompanying plugin-dependency artifact, used to determine whether to * install as a jar or as a directory * @throws MojoExecutionException In the event the plugin should be extracted but cannot, or the file copy fails (in * the event it should not be extracted) * @throws MojoFailureException In the event that the plugins target directory (inside the Eclipse instance * directory) does not exist, or is not a directory. */ private void install(Artifact artifact, MavenProject project) throws MojoExecutionException, MojoFailureException { if (pluginsDir == null) { pluginsDir = new File(eclipseDir, "plugins"); } if (!pluginsDir.exists() || !pluginsDir.isDirectory()) { throw new MojoFailureException("Invalid Eclipse directory: " + eclipseDir + " (plugins directory is missing or not a directory)."); } boolean installAsJar = true; Properties properties = project.getProperties(); if (properties != null) { installAsJar = !Boolean.valueOf(properties.getProperty(PROP_UNPACK_PLUGIN, "false")).booleanValue(); } Attributes attributes = null; try { // don't verify, plugins zipped by eclipse:make-artifacts could have a bad signature JarFile jar = new JarFile(artifact.getFile(), false); Manifest manifest = jar.getManifest(); if (manifest == null) { getLog().debug("Ignoring " + artifact.getArtifactId() + " as it is does not have a Manifest (and so is not an OSGi bundle)"); return; } attributes = manifest.getMainAttributes(); } catch (IOException e) { throw new MojoExecutionException( "Unable to read manifest of plugin " + artifact.getFile().getAbsolutePath(), e); } String pluginName = formatEclipsePluginName(artifact); File pluginFile = new File(pluginsDir, pluginName + ".jar"); File pluginDir = new File(pluginsDir, pluginName); boolean skipped = true; /* check if artifact is an OSGi bundle and ignore if not */ Object bundleName = attributes.getValue("Bundle-Name"); Object bundleSymbolicName = attributes.getValue("Bundle-SymbolicName"); if (bundleSymbolicName == null && bundleName == null) { getLog().debug("Ignoring " + artifact.getArtifactId() + " as it is not an OSGi bundle (no Bundle-SymbolicName or Bundle-Name in manifest)"); return; } if (overwrite) { if (pluginFile.exists() || pluginDir.exists()) { getLog().warn("Overwriting old plugin with contents of: " + artifact.getId()); getLog().debug("Removing old plugin from both: " + pluginFile + " and: " + pluginDir); try { FileUtils.forceDelete(pluginDir); FileUtils.forceDelete(pluginFile); } catch (IOException e) { throw new MojoExecutionException( "Failed to remove old plugin from: " + pluginFile + " or: " + pluginDir, e); } getLog().debug("Removal of old plugin is complete; proceeding with plugin installation."); } performFileOperations(installAsJar, artifact, pluginFile, pluginDir); skipped = false; } else if (installAsJar && !pluginFile.exists()) { performFileOperations(installAsJar, artifact, pluginFile, pluginDir); skipped = false; } else if (!installAsJar && !pluginDir.exists()) { performFileOperations(installAsJar, artifact, pluginFile, pluginDir); skipped = false; } if (skipped) { if (installAsJar) { getLog().info("Skipping plugin installation for: " + artifact.getId() + "; file: " + pluginFile + " already exists. Set overwrite = true to override this."); } else if (!installAsJar) { getLog().info("Skipping plugin installation for: " + artifact.getId() + "; directory: " + pluginDir + " already exists. Set overwrite = true to override this."); } } }
From source file:com.alibaba.citrus.maven.eclipse.base.ide.IdeUtils.java
License:Apache License
/** * Returns the source encoding configured for the compiler plugin. Returns the minimum version required to compile * both standard and test sources, if settings are different. * * @param project maven project//from w w w. ja v a 2s . c o m * @return java source version */ public static String getCompilerSourceEncoding(MavenProject project) { String value = IdeUtils.getCompilerPluginSetting(project, PROPERTY_ENCODING); if (value == null) { project.getProperties().getProperty("project.build.sourceEncoding"); } return value; }
From source file:com.carrotgarden.m2e.config.LaunchDelegate.java
License:BSD License
private void launchMaven(final File pomFile, final List<String> commandList, final IProgressMonitor monitor) throws CoreException { final IMaven maven = MavenPlugin.getMaven(); final Model mavenModel = maven.readModel(pomFile); final MavenProject mavenProject = new MavenProject(mavenModel); final Properties mavenProps = mavenProject.getProperties(); for (final Map.Entry<?, ?> entry : mavenProps.entrySet()) { final String key = entry.getKey().toString(); final String value = entry.getValue().toString(); // ConfigPlugin.logInfo("key= " + key + " value=" + value); }// w w w . j a v a 2 s .c om // final List<String> goalList = new LinkedList<String>(); final List<String> profileActiveList = new LinkedList<String>(); final List<String> profileInactiveList = new LinkedList<String>(); for (final String command : commandList) { if (command.startsWith("-")) { /** command line options */ if (command.startsWith("--activate-profiles")) { ConfigPlugin.log(IStatus.ERROR, "TODO : " + command); } else { ConfigPlugin.log(IStatus.ERROR, "not supported : " + command); } } else { /** maven execution goals */ goalList.add(command); } } // final MavenExecutionRequest request = maven.createExecutionRequest(monitor); request.setPom(pomFile); request.setGoals(goalList); // TODO // request.setActiveProfiles(profileActiveList); // request.setInactiveProfiles(profileInactiveList); // final String id = mavenProject.getId(); ConfigPlugin.log(IStatus.INFO, "maven execute : " + mavenProject.getId() + " " + MojoUtil.join(commandList, ",")); // final Job job = new Job(id) { // { // setSystem(true); // setPriority(BUILD); // } // @Override // protected IStatus run(final IProgressMonitor monitor) { // return null; // } // }; final MavenExecutionResult result = maven.execute(request, monitor); if (result.hasExceptions()) { throw new CoreException(new Status(IStatus.ERROR, ConfigPlugin.ID, "maven execution failed", result.getExceptions().get(0))); } }
From source file:com.edugility.jpa.maven.plugin.ListEntityClassnamesMojo.java
License:Open Source License
/** * Executes this mojo.// w w w .j a va 2 s .c o m * * @exception MojoExecutionException if this mojo could not be executed * * @exception MojoFailureException if the build should fail */ @Override public void execute() throws MojoExecutionException, MojoFailureException { final Log log = this.getLog(); if (log == null) { throw new MojoExecutionException("this.getLog() == null"); } try { this.initialize(); } catch (final DependencyResolutionRequiredException kaboom) { throw new MojoExecutionException(String.format( "Dependencies of the current Maven project could not be downloaded during initialization of the jpa-maven-plugin."), kaboom); } catch (final NotWritableDirectoryException kaboom) { throw new MojoExecutionException(String.format( "The output directory path, %s, exists and is a directory, but the current user, %s, cannot write to it.", kaboom.getFile(), System.getProperty("user.name")), kaboom); } catch (final NotWritableFileException kaboom) { throw new MojoExecutionException(String.format( "The outputFile specified, %s, is a regular file, but cannot be written to by Maven running as user %s. The outputFile parameter must designate either an existing, writable file or a non-existent file.", outputFile, System.getProperty("user.name")), kaboom); } catch (final NotNormalFileException kaboom) { throw new MojoExecutionException(String.format( "The outputFile specified, %s, is not a directory, but is also not a normal file. The outputFile parameter must deisgnate either an existing, writable, normal file or a non-existent file.", outputFile), kaboom); } catch (final NotDirectoryException kaboom) { throw new MojoExecutionException(String.format( "The output directory path, %s, exists but is not a directory.", kaboom.getFile()), kaboom); } catch (final PathCreationFailedException kaboom) { throw new MojoExecutionException( String.format("Some portion of the output directory path, %s, could not be created.", kaboom.getFile()), kaboom); } catch (final FileException other) { throw new MojoExecutionException("An unexpected FileException occurred during initialization.", other); } // Scan the test classpath for Entity, MappedSuperclass, IdClass, // Embeddable, etc. annotations. final AnnotationDB db; AnnotationDB tempDb = null; try { tempDb = this.scan(); } catch (final IOException kaboom) { throw new MojoExecutionException( "Execution failed because an IOException was encountered during URL scanning.", kaboom); } finally { db = tempDb; tempDb = null; } assert db != null; if (log.isDebugEnabled()) { log.debug("Annotation index:"); final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); db.outputAnnotationIndex(pw); log.debug(sw.toString()); try { sw.close(); } catch (final IOException ignored) { // ignored on purpose } pw.close(); } final Properties properties = new Properties(); // Having scanned the classpaths, get the "index", which is a Map // of classnames indexed by annotation classnames. final Map<String, Set<String>> ai = db.getAnnotationIndex(); if (ai == null) { if (log.isWarnEnabled()) { log.warn("After scanning for Entities, a null annotation index was returned by the AnnotationDB."); } } else if (ai.isEmpty()) { if (log.isWarnEnabled()) { log.warn("After scanning for Entities, no annotated Entities were found."); } } else { final Map<String, Set<String>> propertyNameIndex = new HashMap<String, Set<String>>(); // For each of the annotations we are interested in, do some // work on the classes that sport those annotations. for (final String jpaAnnotation : JPA_ANNOTATIONS) { // Find all classnames annotated with that annotation // (e.g. @Entity, @MappedSuperclass, etc.). final Set<String> annotatedClassNames = ai.get(jpaAnnotation); if (annotatedClassNames != null && !annotatedClassNames.isEmpty()) { for (final String annotatedClassName : annotatedClassNames) { assert annotatedClassName != null; // For every classname we find, see which property name it // is going to be assigned to. For example, we might be // configured so that com.foobar.* get assigned to the // foobarClassnames property. final String propertyName = this.determinePropertyName(annotatedClassName); assert propertyName != null; Set<String> relevantClassNames = propertyNameIndex.get(propertyName); if (relevantClassNames == null) { relevantClassNames = new TreeSet<String>(); propertyNameIndex.put(propertyName, relevantClassNames); } assert relevantClassNames != null; // Add the annotated class to the set of other annotated // classnames stored under that property. relevantClassNames.add(annotatedClassName); } } } final Set<Entry<String, Set<String>>> entrySet = propertyNameIndex.entrySet(); assert entrySet != null; if (!entrySet.isEmpty()) { final String firstItemPrefix = this.getFirstItemPrefix(); final String prefix = this.getPrefix(); final String suffix = this.getSuffix(); final String lastItemSuffix = this.getLastItemSuffix(); for (final Entry<String, Set<String>> entry : entrySet) { assert entry != null; // For every entry indexing a set of classes under a property // name, stringify the set of classnames into a single // StringBuilder. Index that stringified set under the // property name. This Properties will be the contents of our file. final StringBuilder sb = new StringBuilder(); final String propertyName = entry.getKey(); assert propertyName != null; final Set<String> classNames = entry.getValue(); assert classNames != null; assert !classNames.isEmpty(); final Iterator<String> classNamesIterator = classNames.iterator(); assert classNamesIterator != null; assert classNamesIterator.hasNext(); while (classNamesIterator.hasNext()) { sb.append(this.decorate(classNamesIterator.next(), sb.length() <= 0 ? firstItemPrefix : prefix, classNamesIterator.hasNext() ? suffix : lastItemSuffix)); } properties.setProperty(propertyName, sb.toString()); } } } if (log.isDebugEnabled()) { final Enumeration<?> propertyNames = properties.propertyNames(); if (propertyNames != null) { while (propertyNames.hasMoreElements()) { final Object nextElement = propertyNames.nextElement(); if (nextElement != null) { final String key = nextElement.toString(); assert key != null; final String value = properties.getProperty(key); log.debug(String.format("%s = %s", key, value)); } } } } final MavenProject project = this.getProject(); if (project != null) { final Properties projectProperties = project.getProperties(); if (projectProperties != null) { @SuppressWarnings("unchecked") final Enumeration<String> propertyNames = (Enumeration<String>) properties.propertyNames(); if (propertyNames != null && propertyNames.hasMoreElements()) { while (propertyNames.hasMoreElements()) { final String propertyName = propertyNames.nextElement(); if (propertyName != null) { projectProperties.setProperty(propertyName, properties.getProperty(propertyName)); } } } } } if (this.getUseOutputFile()) { final File outputFile = this.getOutputFile(); if (outputFile != null) { assert outputFile.exists() ? outputFile.isFile() : true; assert outputFile.getParentFile() != null; assert outputFile.getParentFile().isDirectory(); assert outputFile.getParentFile().canWrite(); assert !outputFile.exists() ? outputFile.getParentFile().canWrite() : true; // Prepare to write. Get the character encoding, accounting for // possible null return values from an overridden getEncoding() // method. String encoding = this.getEncoding(); if (encoding == null) { encoding = ""; } else { encoding = encoding.trim(); } if (encoding.isEmpty()) { encoding = "UTF8"; } // Set up the Writer to point to the outputFile and have the // Properties store itself there. Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), encoding)); properties.store(writer, "Generated by " + this.getClass().getName()); writer.flush(); } catch (final IOException kaboom) { throw new MojoExecutionException(String.format( "While attempting to write to the outputFile parameter (%s), an IOException was encountered.", outputFile), kaboom); } finally { if (writer != null) { try { writer.close(); } catch (final IOException ignore) { // ignored on purpose } } } } } }
From source file:com.fibon.maven.confluence.helpers.TemplateEvaluator.java
License:Apache License
public TemplateEvaluator(MavenProject project) { if (project != null) { context.put("project", project); for (Entry<Object, Object> p : project.getProperties().entrySet()) { context.put(p.getKey().toString(), p.getValue()); }/* w ww .j av a2s . c om*/ } }
From source file:com.github.htfv.maven.plugins.buildconfigurator.core.configurators.propertyfiles.PropertyFileConfigurator.java
License:Apache License
/** * Updates project properties. Properties are immutable - if there is * already a user or a project property with the same key defined, it will * not be overwritten./* w w w. jav a 2s. c om*/ * * @param ctx * The configuration context. * @param resultBuilder * The result builder. */ private void updateProjectProperties(final ConfigurationContext ctx, final Result.Builder resultBuilder) { final Configuration properties = ctx.getProperties(); final MavenProject project = ctx.getProject(); final Properties projectProperties = project.getProperties(); final Properties userProperties = project.getProjectBuildingRequest().getUserProperties(); @SuppressWarnings("unchecked") final Iterator<String> keys = properties.getKeys(); while (keys.hasNext()) { final String key = keys.next(); if (userProperties.containsKey(key) || projectProperties.containsKey(key)) { continue; } final String value = ctx.getStringValue(properties.getString(key)); projectProperties.setProperty(key, value); resultBuilder.newProperty(key, value); } }
From source file:com.github.htfv.maven.plugins.eclipseconfigurator.utils.ECELUtils.java
License:Apache License
public static ELContext createELContext(final MavenProject mavenProject) { final Map<String, Object> implicitObjects = new HashMap<String, Object>(); implicitObjects.put("project", mavenProject); return createELContext(new MapPropertySource(implicitObjects), new PropertiesPropertySource(mavenProject.getProjectBuildingRequest().getUserProperties()), new PropertiesPropertySource(mavenProject.getProperties())); }
From source file:com.github.maven_nar.NarProperties.java
License:Apache License
private NarProperties(final MavenProject project) throws MojoFailureException { final Properties defaults = PropertyUtils.loadProperties(NarUtil.class.getResourceAsStream(AOL_PROPERTIES)); if (defaults == null) { throw new MojoFailureException( "NAR: Could not load default properties file: '" + AOL_PROPERTIES + "'."); }//from w w w . j av a 2 s.co m this.properties = new Properties(defaults); FileInputStream fis = null; String customPropertyLocation = null; try { if (project != null) { customPropertyLocation = project.getProperties().getProperty(CUSTOM_AOL_PROPERTY_KEY); if (customPropertyLocation == null) { // Try and read from the system property in case it's specified there customPropertyLocation = System.getProperties().getProperty(CUSTOM_AOL_PROPERTY_KEY); } fis = new FileInputStream(customPropertyLocation != null ? customPropertyLocation : project.getBasedir() + File.separator + AOL_PROPERTIES); this.properties.load(fis); } } catch (final FileNotFoundException e) { if (customPropertyLocation != null) { // We tried loading from a custom location - so throw the exception throw new MojoFailureException( "NAR: Could not load custom properties file: '" + customPropertyLocation + "'."); } } catch (final IOException e) { // ignore (FIXME) } finally { try { if (fis != null) { fis.close(); } } catch (final IOException e) { // ignore } } }
From source file:com.github.shyiko.sme.ServersExtension.java
License:Apache License
@Override public void afterProjectsRead(MavenSession session) throws MavenExecutionException { MojoExecution mojoExecution = new MojoExecution(new MojoDescriptor()); ExpressionEvaluator expressionEvaluator = new PluginParameterExpressionEvaluator(session, mojoExecution); Properties userProperties = session.getUserProperties(); boolean exportAsSysProp = isExtensionProperty(session, "servers.exportAsSysProp"); Map<String, String> properties = new HashMap<String, String>(); try {/*w ww . j a va 2s .co m*/ for (Server server : session.getSettings().getServers()) { String serverId = server.getId(); for (String field : FIELDS) { String[] aliases = getAliases(serverId, field); String fieldNameWithFirstLetterCapitalized = upperCaseFirstLetter(field); String fieldValue = (String) Server.class.getMethod("get" + fieldNameWithFirstLetterCapitalized) .invoke(server); if (fieldValue != null) { fieldValue = decryptInlinePasswords(fieldValue); } for (String alias : aliases) { String userPropertyValue = userProperties.getProperty(alias); if (userPropertyValue != null) { fieldValue = userPropertyValue; break; } } String resolvedValue = (String) expressionEvaluator.evaluate(fieldValue); Server.class .getMethod("set" + fieldNameWithFirstLetterCapitalized, new Class[] { String.class }) .invoke(server, resolvedValue); if (resolvedValue != null) { for (String alias : aliases) { properties.put(alias, resolvedValue); } } } } if (exportAsSysProp) { System.getProperties().putAll(properties); } else { for (MavenProject project : session.getProjects()) { Properties projectProperties = project.getProperties(); projectProperties.putAll(properties); } } } catch (Exception e) { throw new MavenExecutionException("Failed to expose settings.servers.*", e); } }
From source file:com.liferay.ide.maven.core.LiferayPortalMaven.java
License:Open Source License
@Override public String getVersion() { String retval = null;//from w ww . j av a2 s . co m final IMavenProjectFacade projectFacade = MavenUtil.getProjectFacade(this.lrMvnProject.getProject()); if (projectFacade != null) { try { final MavenProject mavenProject = projectFacade.getMavenProject(new NullProgressMonitor()); String liferayVersion = MavenUtil.getLiferayMavenPluginConfig(mavenProject, ILiferayMavenConstants.PLUGIN_CONFIG_LIFERAY_VERSION); if (liferayVersion == null) { liferayVersion = mavenProject.getProperties().getProperty("liferay.version"); if (liferayVersion == null) { // look through dependencies for portal-service final List<Dependency> deps = mavenProject.getDependencies(); if (deps != null) { for (Dependency dep : deps) { if (dep.getArtifactId().startsWith("portal-") && dep.getGroupId().startsWith("com.liferay")) { liferayVersion = dep.getVersion(); break; } } } } } if (liferayVersion != null) { retval = MavenUtil.getVersion(liferayVersion); } } catch (CoreException e) { } } return retval; }