org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException Java Examples

The following examples show how to use org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JUnitOutputListenerProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String getReportsDirectory(String groupId, String artifactId, String goal, String fallbackExpression) {
    String reportsDirectory = PluginPropertyUtils.getPluginProperty(config.getMavenProject(),
       groupId, artifactId, "reportsDirectory", goal, null); // NOI18N
    if (null == reportsDirectory) {
        // fallback to default value
        try {
            Object defaultValue = PluginPropertyUtils
                .createEvaluator(config.getMavenProject())
                .evaluate(fallbackExpression);
            if (defaultValue instanceof String) {
                reportsDirectory = (String) defaultValue;
            }
        } catch (ExpressionEvaluationException ex) {
            // NOP could not resolved default value
        }
    }
    return reportsDirectory;
}
 
Example #2
Source File: LicenseHeaderPanelProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public FileObject resolveProjectLocation(String path) {
    if ("".equals(path)) {
        return null;
    }
    try {
        String eval = PluginPropertyUtils.createEvaluator(project).evaluate(path).toString();
        FileObject toRet = FileUtil.toFileObject(FileUtilities.resolveFilePath(handle.getProject().getBasedir(), eval));
        if (toRet != null && toRet.isFolder()) {
            toRet = null;
        }
        return toRet;
    } catch (ExpressionEvaluationException ex) {
        Exceptions.printStackTrace(ex);
    }
    return null;
}
 
Example #3
Source File: IncludeProjectDependenciesComponentConfigurator.java    From protostuff with Apache License 2.0 6 votes vote down vote up
private void addProjectDependenciesToClassRealm(ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm)
        throws ComponentConfigurationException
{
    List<String> runtimeClasspathElements;
    try
    {
        // noinspection unchecked
        runtimeClasspathElements = (List<String>) expressionEvaluator
                .evaluate("${project.runtimeClasspathElements}");
    }
    catch (ExpressionEvaluationException e)
    {
        throw new ComponentConfigurationException(
                "There was a problem evaluating: ${project.runtimeClasspathElements}", e);
    }

    // Add the project dependencies to the ClassRealm
    final URL[] urls = buildURLs(runtimeClasspathElements);
    for (URL url : urls)
    {
        containerRealm.addConstituent(url);
    }
}
 
Example #4
Source File: IncludeProjectDependenciesComponentConfigurator.java    From protostuff-compiler with Apache License 2.0 6 votes vote down vote up
private void addProjectDependenciesToClassRealm(ExpressionEvaluator expressionEvaluator, ClassRealm realm)
        throws ComponentConfigurationException {
    List<String> runtimeClasspathElements;
    try {
        // noinspection unchecked
        runtimeClasspathElements = (List<String>) expressionEvaluator
                .evaluate("${project.runtimeClasspathElements}");
    } catch (ExpressionEvaluationException e) {
        throw new ComponentConfigurationException(
                "There was a problem evaluating: ${project.runtimeClasspathElements}", e);
    }

    // Add the project dependencies to the ClassRealm
    final URL[] urls = buildUrls(runtimeClasspathElements);
    for (URL url : urls) {
        realm.addURL(url);
    }
}
 
Example #5
Source File: IncludeProjectDependenciesComponentConfigurator.java    From incubator-hivemall with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static void addProjectDependenciesToClassRealm(
        final ExpressionEvaluator expressionEvaluator, final ClassRealm containerRealm)
        throws ComponentConfigurationException {
    final List<String> runtimeClasspathElements;
    try {
        // noinspection unchecked
        runtimeClasspathElements = (List<String>) expressionEvaluator.evaluate(
            "${project.runtimeClasspathElements}");
    } catch (ExpressionEvaluationException e) {
        throw new ComponentConfigurationException(
            "There was a problem evaluating: ${project.runtimeClasspathElements}", e);
    }

    // Add the project dependencies to the ClassRealm
    final URL[] urls = buildURLs(runtimeClasspathElements);
    for (URL url : urls) {
        containerRealm.addConstituent(url);
    }
}
 
Example #6
Source File: AbstractRequireRoles.java    From extra-enforcer-rules with Apache License 2.0 5 votes vote down vote up
/**
 * Extracted for easier testability.
 *
 * @param helper
 * @return the MavenProject enforcer is running on.
 *
 * @throws EnforcerRuleException
 */
MavenProject getMavenProject( EnforcerRuleHelper helper ) throws EnforcerRuleException
{
    try
    {
        return ( MavenProject ) helper.evaluate( "${project}" );
    }
    catch ( ExpressionEvaluationException eee )
    {
        throw new EnforcerRuleException( "Unable to get project.", eee );
    }
}
 
Example #7
Source File: IncludeProjectDependenciesComponentConfigurator.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void addProjectDependenciesToClassRealm(ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm) throws ComponentConfigurationException {
    List<String> compileClasspathElements;
    try {
        //noinspection unchecked
        compileClasspathElements = (List<String>) expressionEvaluator.evaluate("${project.compileClasspathElements}");
    } catch (ExpressionEvaluationException e) {
        throw new ComponentConfigurationException("There was a problem evaluating: ${project.compileClasspathElements}", e);
    }

    // Add the project dependencies to the ClassRealm
    final URL[] urls = buildURLs(compileClasspathElements);
    for (URL url : urls) {
        containerRealm.addConstituent(url);
    }
}
 
Example #8
Source File: MyCustomRule.java    From tutorials with MIT License 5 votes vote down vote up
public void execute(EnforcerRuleHelper enforcerRuleHelper) throws EnforcerRuleException {

        try {

            String groupId = (String) enforcerRuleHelper.evaluate("${project.groupId}");

            if (groupId == null || !groupId.startsWith("com.baeldung")) {
                throw new EnforcerRuleException("Project group id does not start with com.baeldung");
            }

        }
        catch (ExpressionEvaluationException ex ) {
            throw new EnforcerRuleException( "Unable to lookup an expression " + ex.getLocalizedMessage(), ex );
        }
    }
 
Example #9
Source File: BuildMojo.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private String expand(final String raw) throws MojoExecutionException {
  final Object value;
  try {
    value = expressionEvaluator.evaluate(raw);
  } catch (ExpressionEvaluationException e) {
    throw new MojoExecutionException("Expression evaluation failed: " + raw, e);
  }

  if (value == null) {
    throw new MojoExecutionException("Undefined expression: " + raw);
  }

  return value.toString();
}
 
Example #10
Source File: RequirePropertyDivergesTest.java    From extra-enforcer-rules with Apache License 2.0 5 votes vote down vote up
void setUpHelper( final MavenProject project, final String propertyValue ) throws RuntimeException
{
    try
    {
        when( helper.evaluate( "${project}" ) ).thenReturn( project );
        when( helper.evaluate( "${checkedProperty}" ) ).thenReturn( propertyValue );
    }
    catch ( ExpressionEvaluationException ex )
    {
        throw new RuntimeException( ex );
    }
    when( helper.getLog() ).thenReturn( mock( Log.class ) );
}
 
Example #11
Source File: RequirePropertyDivergesTest.java    From extra-enforcer-rules with Apache License 2.0 5 votes vote down vote up
void testCheckAgainstParentValue( final String parentGroupId, final String childGroupId ) throws ExpressionEvaluationException, EnforcerRuleException
{
    instance.setProperty( "project.groupId" );
    MavenProject parent = createMavenProject( parentGroupId, "parent-pom" );
    MavenProject project = createMavenProject( childGroupId, "child" );
    project.setParent( parent );
    when( helper.evaluate( "${project.parent.groupId}" ) ).thenReturn( parentGroupId );
    instance.checkAgainstParentValue( project, parent, helper, childGroupId );
}
 
Example #12
Source File: RequirePropertyDivergesTest.java    From extra-enforcer-rules with Apache License 2.0 5 votes vote down vote up
@Test( expected = EnforcerRuleException.class )
public void testGetPropertyValueFail() throws ExpressionEvaluationException, EnforcerRuleException
{
    when( helper.evaluate( "${checkedProperty}" ) ).thenThrow( ExpressionEvaluationException.class );
    instance.setProperty( "checkedProperty" );
    instance.getPropertyValue( helper );
}
 
Example #13
Source File: LinkageCheckerRuleTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setup()
    throws ExpressionEvaluationException, ComponentLookupException,
    DependencyResolutionException, URISyntaxException {
  repositorySystem = RepositoryUtility.newRepositorySystem();
  repositorySystemSession = RepositoryUtility.newSession(repositorySystem);
  dummyArtifactWithFile = createArtifactWithDummyFile("a:b:0.1");
  setupMock();
}
 
Example #14
Source File: RequirePropertyDiverges.java    From extra-enforcer-rules with Apache License 2.0 5 votes vote down vote up
/**
 * Extracted for easier testability.
 *
 * @param helper
 * @return the MavenProject enforcer is running on.
 *
 * @throws EnforcerRuleException
 */
MavenProject getMavenProject( EnforcerRuleHelper helper ) throws EnforcerRuleException
{
    try
    {
        return ( MavenProject ) helper.evaluate( "${project}" );
    }
    catch ( ExpressionEvaluationException eee )
    {
        throw new EnforcerRuleException( "Unable to get project.", eee );
    }
}
 
Example #15
Source File: HyperlinkProviderImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
String[] getTooltipText() {
    if (isText) {
        //we are in element text
        String text = ftext;
        int tokenOff = ftokenOff;
        if (isMavenProperty()) {
            Tuple tup = findProperty(text, tokenOff, documentOffset);

            if (tup != null) {
                String prop = tup.value.substring("${".length(), tup.value.length() - 1); //remove the brackets
                try {
                    Project nbprj = getProject(doc);
                    if (nbprj != null) {
                        Object exRes = PluginPropertyUtils.createEvaluator(nbprj).evaluate(tup.value);
                        if (exRes != null) {
                            return new String[]{prop, (String) exRes};
                        }
                    } else {
                        //pom file in repository or settings file.
                    }
                } catch (ExpressionEvaluationException ex) {
                    return null;
                }
            }
        } else if (isMavenDependency()) {
            return new String[]{getMavenArtifactAbsolutePomPath()};
        }
    }
    return null;
}
 
Example #16
Source File: LinkageCheckerRuleTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
private void setupMock()
    throws ExpressionEvaluationException, ComponentLookupException,
    DependencyResolutionException {
  mockProject = mock(MavenProject.class);
  mockMavenSession = mock(MavenSession.class);
  when(mockMavenSession.getRepositorySession()).thenReturn(repositorySystemSession);
  mockRuleHelper = mock(EnforcerRuleHelper.class);
  mockProjectDependenciesResolver = mock(ProjectDependenciesResolver.class);
  mockDependencyResolutionResult = mock(DependencyResolutionResult.class);
  mockLog = mock(Log.class);
  when(mockRuleHelper.getLog()).thenReturn(mockLog);
  when(mockRuleHelper.getComponent(ProjectDependenciesResolver.class))
      .thenReturn(mockProjectDependenciesResolver);
  when(mockProjectDependenciesResolver.resolve(any(DependencyResolutionRequest.class)))
      .thenReturn(mockDependencyResolutionResult);
  when(mockRuleHelper.evaluate("${session}")).thenReturn(mockMavenSession);
  when(mockRuleHelper.evaluate("${project}")).thenReturn(mockProject);
  mockMojoExecution = mock(MojoExecution.class);
  when(mockMojoExecution.getLifecyclePhase()).thenReturn("verify");
  when(mockRuleHelper.evaluate("${mojoExecution}")).thenReturn(mockMojoExecution);
  org.apache.maven.artifact.DefaultArtifact rootArtifact =
      new org.apache.maven.artifact.DefaultArtifact(
          "com.google.cloud",
          "linkage-checker-rule-test",
          "0.0.1",
          "compile",
          "jar",
          null,
          new DefaultArtifactHandler());
  rootArtifact.setFile(new File("dummy.jar"));
  when(mockProject.getArtifact()).thenReturn(rootArtifact);
}
 
Example #17
Source File: RequirePropertyDiverges.java    From extra-enforcer-rules with Apache License 2.0 5 votes vote down vote up
/**
 * Extracted for easier testability.
 *
 * @param helper
 * @param propertyName name of the property to extract.
 * @return the value of the property.
 * @throws EnforcerRuleException
 */
Object getPropertyValue( EnforcerRuleHelper helper, final String propertyName ) throws EnforcerRuleException
{
    try
    {
        return helper.evaluate( "${" + propertyName + "}" );
    }
    catch ( ExpressionEvaluationException eee )
    {
        throw new EnforcerRuleException( "Unable to evaluate property: " + propertyName, eee );
    }
}
 
Example #18
Source File: WebProjectWebRootProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> build(Xpp3Dom configRoot, ExpressionEvaluator eval) {
    List<String> webRoots = new ArrayList<>();

    if (configRoot != null) {
        Xpp3Dom webResources = configRoot.getChild("webResources"); // NOI18N
        if (webResources != null) {
            Xpp3Dom[] resources = webResources.getChildren("resource"); // NOI18N

            for (Xpp3Dom resource : resources) {
                if (resource != null) {
                    Xpp3Dom directory = resource.getChild("directory"); // NOI18N

                    if (directory != null) {
                        try {
                            String directoryValue = (String) eval.evaluate(directory.getValue());
                            if (directoryValue != null && !"".equals(directoryValue.trim())) { // NOI18N
                                webRoots.add(directoryValue);
                            }
                        } catch (ExpressionEvaluationException ex) {
                            Exceptions.printStackTrace(ex);
                        }
                    }
                }
            }
        }
    }
    return webRoots;
}
 
Example #19
Source File: ReleaseUtil.java    From unleash-maven-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Calculates an SCM tag name based on a pattern. This pattern can include every parameter reference that can be
 * resolved by <a href=
 * "https://maven.apache.org/ref/3.3.9/maven-core/apidocs/org/apache/maven/plugin/PluginParameterExpressionEvaluator.html">PluginParameterExpressionEvaluator</a>.
 *
 * @param pattern the pattern for the tag name which may contain variables listed above.
 * @param project the Maven project to be used for version calculation during parameter resolution.
 * @param evaluator the Maven plugin parameter expression evaluator used to evaluate expressions containing parameter
 *          references.
 * @return the name of the tag derived from the pattern.
 */
public static String getTagName(String pattern, MavenProject project, PluginParameterExpressionEvaluator evaluator) {
  Preconditions.checkArgument(pattern != null, "Need a tag name pattern to calculate the tag name.");
  Preconditions.checkArgument(evaluator != null, "Need an expression evaluator to calculate the tag name.");

  try {
    StringBuilder sb = new StringBuilder(pattern);
    int start = -1;
    while ((start = sb.indexOf("@{")) > -1) {
      int end = sb.indexOf("}");
      String var = sb.substring(start + 2, end);
      String resolved;
      // the parameter project.version gets a special treatment and will not be resolved by the evaluator but gets the
      // release version instead
      if (Objects.equal("project.version", var)) {
        resolved = MavenVersionUtil.calculateReleaseVersion(project.getVersion());
      } else {
        String expression = "${" + var + "}";
        resolved = evaluator.evaluate(expression).toString();
      }
      sb.replace(start, end + 1, resolved);
    }
    return sb.toString();
  } catch (ExpressionEvaluationException e) {
    throw new RuntimeException("Could not resolve expressions in pattern: " + pattern, e);
  }
}
 
Example #20
Source File: RequirePropertyDivergesTest.java    From extra-enforcer-rules with Apache License 2.0 4 votes vote down vote up
@Test( expected = EnforcerRuleException.class )
public void testGetProjectFail() throws ExpressionEvaluationException, EnforcerRuleException
{
    when( helper.evaluate( "${project}" ) ).thenThrow( ExpressionEvaluationException.class );
    instance.getMavenProject( helper );
}
 
Example #21
Source File: RequirePropertyDivergesTest.java    From extra-enforcer-rules with Apache License 2.0 4 votes vote down vote up
@Test( expected = EnforcerRuleException.class )
public void testCheckAgainstParentValueFailing() throws EnforcerRuleException, ExpressionEvaluationException
{
    testCheckAgainstParentValue( "company.parent-pom", "company.parent-pom" );
}
 
Example #22
Source File: RequirePropertyDivergesTest.java    From extra-enforcer-rules with Apache License 2.0 4 votes vote down vote up
@Test
public void testCheckAgainstParentValue() throws EnforcerRuleException, ExpressionEvaluationException
{
    testCheckAgainstParentValue( "company.parent-pom", "company.project1" );
}
 
Example #23
Source File: EarImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private MavenModule[] checkConfiguration(MavenProject prj, Object conf) {
    List<MavenModule> toRet = new ArrayList<MavenModule>();
    if (conf != null && conf instanceof Xpp3Dom) {
        ExpressionEvaluator eval = PluginPropertyUtils.createEvaluator(project);
        Xpp3Dom dom = (Xpp3Dom) conf;
        Xpp3Dom modules = dom.getChild("modules"); //NOI18N
        if (modules != null) {
            int index = 0;
            for (Xpp3Dom module : modules.getChildren()) {
                MavenModule mm = new MavenModule();
                mm.type = module.getName();
                if (module.getChildren() != null) {
                    for (Xpp3Dom param : module.getChildren()) {
                        String value = param.getValue();
                        if (value == null) {
                            continue;
                        }
                        try {
                            Object evaluated = eval.evaluate(value.trim());
                            value = evaluated != null ? ("" + evaluated) : value.trim();  //NOI18N
                        } catch (ExpressionEvaluationException e) {
                            //log silently
                        }
                        if ("groupId".equals(param.getName())) { //NOI18N
                            mm.groupId = value;
                        } else if ("artifactId".equals(param.getName())) { //NOI18N
                            mm.artifactId = value;
                        } else if ("classifier".equals(param.getName())) { //NOI18N
                            mm.classifier = value;
                        } else if ("uri".equals(param.getName())) { //NOI18N
                            mm.uri = value;
                        } else if ("bundleDir".equals(param.getName())) { //NOI18N
                            mm.bundleDir = value;
                        } else if ("bundleFileName".equals(param.getName())) { //NOI18N
                            mm.bundleFileName = value;
                        } else if ("excluded".equals(param.getName())) { //NOI18N
                            mm.excluded = Boolean.valueOf(value);
                        }
                    }
                }
                mm.pomIndex = index;
                index++;
                toRet.add(mm);
            }
        }
    }
    return toRet.toArray(new MavenModule[0]);
}
 
Example #24
Source File: RequireEncoding.java    From extra-enforcer-rules with Apache License 2.0 4 votes vote down vote up
public void execute( EnforcerRuleHelper helper )
    throws EnforcerRuleException
{
    try
    {
        if ( StringUtils.isBlank( encoding ) )
        {
            encoding = (String) helper.evaluate( "${project.build.sourceEncoding}" );
        }
        Log log = helper.getLog();

        Set< String > acceptedEncodings = new HashSet< String >( Arrays.asList( encoding ) );
        if ( encoding.equals( StandardCharsets.US_ASCII.name() ) )
        {
            log.warn( "Encoding US-ASCII is hard to detect. Use UTF-8 or ISO-8859-1" );
        }

        if ( acceptAsciiSubset && ( encoding.equals( StandardCharsets.ISO_8859_1.name() ) || encoding.equals( StandardCharsets.UTF_8.name() ) ) )
        {
            acceptedEncodings.add( StandardCharsets.US_ASCII.name() );
        }

        String basedir = (String) helper.evaluate( "${basedir}" );
        DirectoryScanner ds = new DirectoryScanner();
        ds.setBasedir( basedir );
        if ( StringUtils.isNotBlank( includes ) )
        {
            ds.setIncludes( includes.split( "[,\\|]" ) );
        }
        if ( StringUtils.isNotBlank( excludes ) )
        {
            ds.setExcludes( excludes.split( "[,\\|]" ) );
        }
        if ( useDefaultExcludes )
        {
            ds.addDefaultExcludes();
        }
        ds.scan();
        StringBuilder filesInMsg = new StringBuilder();
        for ( String file : ds.getIncludedFiles() )
        {
            String fileEncoding = getEncoding( encoding, new File( basedir, file ), log );
            if ( log.isDebugEnabled() )
            {
                log.debug( file + "==>" + fileEncoding );
            }
            if ( fileEncoding != null && !acceptedEncodings.contains( fileEncoding ) )
            {
                filesInMsg.append( file );
                filesInMsg.append( "==>" );
                filesInMsg.append( fileEncoding );
                filesInMsg.append( "\n" );
                if ( failFast )
                {
                    throw new EnforcerRuleException( filesInMsg.toString() );
                }
            }
        }
        if ( filesInMsg.length() > 0 )
        {
            throw new EnforcerRuleException( "Files not encoded in " + encoding + ":\n" + filesInMsg );
        }
    }
    catch ( IOException ex )
    {
        throw new EnforcerRuleException( "Reading Files", ex );
    }
    catch ( ExpressionEvaluationException e )
    {
        throw new EnforcerRuleException( "Unable to lookup an expression " + e.getLocalizedMessage(), e );
    }
}
 
Example #25
Source File: HyperlinkProviderImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void calculateInfo(Token<XMLTokenId> token, TokenSequence<XMLTokenId> xml) {
    isText = token.id() == XMLTokenId.TEXT;
    if (isText) {
        ftokenOff = xml.offset();
        ftext = token.text().toString();

        if (projectFileObject != null && getPath(projectFileObject, ftext) != null) {
            xml.movePrevious();
            token = xml.token();
            if (token != null && token.id().equals(XMLTokenId.TAG) && TokenUtilities.equals(token.text(), ">")) {//NOI18N
                xml.movePrevious();
                token = xml.token();
                if (token != null && token.id().equals(XMLTokenId.TAG)) {
                    if (TokenUtilities.equals(token.text(), "<module")) {//NOI18N
                        if (!ftext.endsWith("/pom.xml")) {
                            ftext += "/pom.xml"; //NOI18N
                        }
                    }
                }
            }
        } else {
            xml.movePrevious();
            token = xml.token();
            if (token != null && token.id().equals(XMLTokenId.TAG) && TokenUtilities.equals(token.text(), ">")) { //NOI18N
                xml.movePrevious();
                String tokenString = xml.token().text().toString();
                if ("<artifactId".equals(tokenString) || //NOI18N
                        "<groupId".equals(tokenString) || //NOI18N
                        "<type".equals(tokenString) || //NOI18N
                        ("<version".equals(tokenString) && !ftext.startsWith("${"))) { 
                    
                    resetSequenceToDependencytagToken(xml);
                    
                    if (TokenUtilities.equals(xml.token().text(), "<dependency")) {          //NOI18N
                        
                        while (!TokenUtilities.equals(xml.token().text(), "</dependency")) { //NOI18N
                            
                            switch (xml.token().text().toString()) {
                                case "<artifactId":
                                    moveToXmlTokenById(xml, XMLTokenId.TEXT);
                                    token = xml.token();
                                    artifactId = token.text().toString();
                                    break;
                                case "<groupId":
                                    moveToXmlTokenById(xml, XMLTokenId.TEXT);
                                    token = xml.token();
                                    groupId = token.text().toString();
                                    break;
                                case "<version":
                                    moveToXmlTokenById(xml, XMLTokenId.TEXT);
                                    token = xml.token();
                                    if (TokenUtilities.startsWith(token.text(), "${")) { //NOI18N
                                        Project nbprj = getProject(doc);
                                        if (nbprj != null) {
                                            try {
                                                version = (String) PluginPropertyUtils.createEvaluator(nbprj).evaluate(token.text().toString());
                                            } catch (ExpressionEvaluationException eee) {
                                                LOG.log(Level.INFO, "Unable to evaluate property: " + token.text().toString(), eee);
                                            }
                                        }
                                    } else {
                                        version = token.text().toString();
                                    }
                                    break;
                                case "<type" :
                                    moveToXmlTokenById(xml, XMLTokenId.TEXT);
                                    token = xml.token();
                                    type = token.text().toString();
                                    break;
                            }
                            xml.moveNext();
                            moveToXmlTokenById(xml, XMLTokenId.TAG);
                        }
                        // handle cases where the version element is covered in a 
                        // parent pom/dependenciesManagement
                        if (version == null) {
                            NbMavenProject projectForDocument = getNbMavenProject(doc);
                            if (projectForDocument != null) {
                                MavenProject mavenProject = projectForDocument.getMavenProject();
                                for (Artifact artifact : mavenProject.getArtifacts()) {
                                    if (artifact.getGroupId().equals(groupId)
                                            && artifact.getArtifactId().equals(artifactId)) {
                                        version = artifact.getVersion();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
 
Example #26
Source File: PomHelper.java    From versions-maven-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Takes a list of {@link org.apache.maven.model.Plugin} instances and adds associations to properties used to
 * define versions of the plugin artifact or any of the plugin dependencies specified in the pom.
 *
 * @param helper Our helper.
 * @param expressionEvaluator Our expression evaluator.
 * @param result The map of {@link org.codehaus.mojo.versions.api.PropertyVersionsBuilder} keyed by property name.
 * @param plugins The list of {@link org.apache.maven.model.Plugin}.
 * @throws ExpressionEvaluationException if an expression cannot be evaluated.
 */
private static void addPluginAssociations( VersionsHelper helper, ExpressionEvaluator expressionEvaluator,
                                           Map<String, PropertyVersionsBuilder> result, List<Plugin> plugins )
    throws ExpressionEvaluationException
{
    if ( plugins == null )
    {
        return;
    }
    for ( Plugin plugin : plugins )
    {
        String version = plugin.getVersion();
        if ( version != null && version.contains( "${" ) && version.indexOf( '}' ) != -1 )
        {
            version = StringUtils.deleteWhitespace( version );
            for ( PropertyVersionsBuilder property : result.values() )
            {
                // any of these could be defined by a property
                final String propertyRef = "${" + property.getName() + "}";
                if ( version.contains( propertyRef ) )
                {
                    String groupId = plugin.getGroupId();
                    if ( groupId == null || groupId.trim().length() == 0 )
                    {
                        // group Id has a special default
                        groupId = APACHE_MAVEN_PLUGINS_GROUPID;
                    }
                    else
                    {
                        groupId = (String) expressionEvaluator.evaluate( groupId );
                    }
                    String artifactId = plugin.getArtifactId();
                    if ( artifactId == null || artifactId.trim().length() == 0 )
                    {
                        // malformed pom
                        continue;
                    }
                    else
                    {
                        artifactId = (String) expressionEvaluator.evaluate( artifactId );
                    }
                    // might as well capture the current value
                    VersionRange versionRange =
                        VersionRange.createFromVersion( (String) expressionEvaluator.evaluate( plugin.getVersion() ) );
                    property.addAssociation( helper.createPluginArtifact( groupId, artifactId, versionRange ),
                                             true );
                    if ( !propertyRef.equals( version ) )
                    {
                        addBounds( property, version, propertyRef, versionRange.toString() );
                    }
                }
            }
        }
        addDependencyAssocations( helper, expressionEvaluator, result, plugin.getDependencies(), true );
    }
}
 
Example #27
Source File: PomHelper.java    From versions-maven-plugin with Apache License 2.0 4 votes vote down vote up
private static void addReportPluginAssociations( VersionsHelper helper, ExpressionEvaluator expressionEvaluator,
                                                 Map<String, PropertyVersionsBuilder> result,
                                                 List<ReportPlugin> reportPlugins )
    throws ExpressionEvaluationException
{
    if ( reportPlugins == null )
    {
        return;
    }
    for ( ReportPlugin plugin : reportPlugins )
    {
        String version = plugin.getVersion();
        if ( version != null && version.contains( "${" ) && version.indexOf( '}' ) != -1 )
        {
            version = StringUtils.deleteWhitespace( version );
            for ( PropertyVersionsBuilder property : result.values() )
            {
                final String propertyRef = "${" + property.getName() + "}";
                if ( version.contains( propertyRef ) )
                {
                    // any of these could be defined by a property
                    String groupId = plugin.getGroupId();
                    if ( groupId == null || groupId.trim().length() == 0 )
                    {
                        // group Id has a special default
                        groupId = APACHE_MAVEN_PLUGINS_GROUPID;
                    }
                    else
                    {
                        groupId = (String) expressionEvaluator.evaluate( groupId );
                    }
                    String artifactId = plugin.getArtifactId();
                    if ( artifactId == null || artifactId.trim().length() == 0 )
                    {
                        // malformed pom
                        continue;
                    }
                    else
                    {
                        artifactId = (String) expressionEvaluator.evaluate( artifactId );
                    }
                    // might as well capture the current value
                    VersionRange versionRange =
                        VersionRange.createFromVersion( (String) expressionEvaluator.evaluate( plugin.getVersion() ) );
                    property.addAssociation( helper.createPluginArtifact( groupId, artifactId, versionRange ),
                                             true );
                    if ( !propertyRef.equals( version ) )
                    {
                        addBounds( property, version, propertyRef, versionRange.toString() );
                    }
                }
            }
        }
    }
}
 
Example #28
Source File: PomHelper.java    From versions-maven-plugin with Apache License 2.0 4 votes vote down vote up
private static void addDependencyAssocations( VersionsHelper helper, ExpressionEvaluator expressionEvaluator,
                                              Map<String, PropertyVersionsBuilder> result,
                                              List<Dependency> dependencies, boolean usePluginRepositories )
    throws ExpressionEvaluationException
{
    if ( dependencies == null )
    {
        return;
    }
    for ( Dependency dependency : dependencies )
    {
        String version = dependency.getVersion();
        if ( version != null && version.contains( "${" ) && version.indexOf( '}' ) != -1 )
        {
            version = StringUtils.deleteWhitespace( version );
            for ( PropertyVersionsBuilder property : result.values() )
            {
                final String propertyRef = "${" + property.getName() + "}";
                if ( version.contains( propertyRef ) )
                {
                    // Any of these could be defined by a property
                    String groupId = dependency.getGroupId();
                    if ( groupId == null || groupId.trim().length() == 0 )
                    {
                        // malformed pom
                        continue;
                    }
                    else
                    {
                        groupId = (String) expressionEvaluator.evaluate( groupId );
                    }
                    String artifactId = dependency.getArtifactId();
                    if ( artifactId == null || artifactId.trim().length() == 0 )
                    {
                        // malformed pom
                        continue;
                    }
                    else
                    {
                        artifactId = (String) expressionEvaluator.evaluate( artifactId );
                    }
                    // might as well capture the current value
                    VersionRange versionRange =
                        VersionRange.createFromVersion( (String) expressionEvaluator.evaluate( dependency.getVersion() ) );
                    property.addAssociation( helper.createDependencyArtifact( groupId, artifactId, versionRange,
                                                                              dependency.getType(),
                                                                              dependency.getClassifier(),
                                                                              dependency.getScope(),
                                                                              dependency.isOptional() ),
                                             usePluginRepositories );
                    if ( !propertyRef.equals( version ) )
                    {
                        addBounds( property, version, propertyRef, versionRange.toString() );
                    }
                }
            }
        }
    }
}
 
Example #29
Source File: Info.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Messages({
    "# {0} - dir basename", "LBL_misconfigured_project={0} [unloadable]",
    "# {0} - path to project", "TXT_Maven_project_at=Maven project at {0}"
})
private String getDisplayName(NbMavenProject nb) {
    MavenProject pr = nb.getMavenProject();
    if (NbMavenProject.isErrorPlaceholder(pr)) {
        return LBL_misconfigured_project(project.getProjectDirectory().getNameExt());
    }
    String custom = project.getLookup().lookup(AuxiliaryProperties.class).get(Constants.HINT_DISPLAY_NAME, true);
    if (custom == null) {
        custom = NbPreferences.forModule(Info.class).get(MavenSettings.PROP_PROJECTNODE_NAME_PATTERN, null);
    }
    if (custom != null) {
        //we evaluate because of global property and property in nb-configuration.xml file. The pom.xml originating value should be already resolved.
        ExpressionEvaluator evaluator = PluginPropertyUtils.createEvaluator(project);
        try {
            Object s = evaluator.evaluate(custom);
            if (s != null) {
                //just make sure the name gets resolved
                String ss = s.toString().replace("${project.name)", "" + pr.getGroupId() + ":" + pr.getArtifactId());
                return ss;
            }
        } catch (ExpressionEvaluationException ex) {
            //now just continue to the default processing
            LOG.log(Level.INFO, "bad display name expression:" + custom, ex);
        }
    }

    String toReturn = pr.getName();
    if (toReturn == null) {
        String grId = pr.getGroupId();
        String artId = pr.getArtifactId();
        if (grId != null && artId != null) {
            toReturn = grId + ":" + artId; //NOI18N
        } else {
            toReturn = TXT_Maven_project_at(FileUtil.getFileDisplayName(project.getProjectDirectory()));
        }
    }
    return toReturn;
}
 
Example #30
Source File: PluginPropertyUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Object evaluate(String string) throws ExpressionEvaluationException {
    return string;
}