How to catch exception in a beanshell?

180 views Asked by At

I can use the evaluateBeanshell rule to enforce some convention: no colon's in directories below src.

<plugin>
  <artifactId>maven-enforcer-plugin</artifactId>
  <version>1.4.1</version>
  <executions>
    <execution>
      <id>enforce-beanshell</id>
      <goals>
        <goal>enforce</goal>
      </goals>
      <configuration>
        <rules>
          <evaluateBeanshell>
            <condition>org.codehaus.plexus.util.FileUtils.getDirectoryNames(new File("src"), "**/*:*", null, false).isEmpty()</condition>
          </evaluateBeanshell>
        </rules>
      </configuration>
    </execution>
  </executions>
</plugin>

But some projects don't have an src directory, and the rule will fail hard. I tried setting

<condition>org.codehaus.plexus.util.FileUtils.getDirectoryNames(new File("."), "src/**/[^A-Z]*", null, false).isEmpty()</condition>

How do I safely catch the non-existence of the src directory?

2

There are 2 answers

0
caduceus On BEST ANSWER

This does what I need

<evaluateBeanshell>
  <condition>
    String projectSource = "${project.basedir}" + "/src";
    if (org.codehaus.plexus.util.FileUtils.fileExists(projectSource)){
      List filenames = org.codehaus.plexus.util.FileUtils.getFileNames(
        new File(projectSource),"**/*.*",null,false);

      for (Iterator it = filenames.iterator(); it.hasNext();) {
        String file = it.next();
        String extension = org.codehaus.plexus.util.FileUtils.getExtension(file);

        if (extension.equals(extension.toLowerCase())) {
          it.remove();
        } else {
          print("Invalid filename extension (no capitals): " + projectSource + "/" + file);
        };
      };
      return filenames.isEmpty();
    } else return true;
  </condition>
</evaluateBeanshell>
2
antonyh On

If you want to use Beanshell, you just need something that returns a boolean.

<evaluateBeanshell>
   <condition>new java.io.File("src").exists()</condition>
</evaluateBeanshell>

This will be true if the path exists as a file/folder/symlink, and false otherwise which will break the build.

If you want to check multiple aspects, such as if it exists AND if it's a directory, add multiple conditions:

<evaluateBeanshell>
   <condition>new java.io.File("path").exists()</condition>
   <condition>new java.io.File("path").isDirectory()</condition>
</evaluateBeanshell>

(Arguably there's little point in checking if it exists then if it's a directory, but helps to illustrate the point)

There's plenty more that can be done with Beanshell, if you have to use it. Ultimately though, the 'requireFilesExist' rule is probably a better configuration for the enforcer.