Using EntityFS in a Groovy program

Karl Gustafsson

Revision History
Revision 1.02009.05.29

Table of Contents

Combining filters
Grep with filters
Filters in switch statements

This document contains some notes on how to best use EntityFS from a Groovy program.

Combining filters

All Filter:s extending AbstractConvenientFilter (which all filters bundled with EntityFS do) can be combined using Groovy's & (and), | (or) and ^ (xor) operators. A filter can be negated using the ~ (bitwise negate) operator.

Example 1. Combining filters

import org.entityfs.util.Directories
import org.entityfs.util.filter.entity.*

// Get all files in the directory d that does not end with .xml or .xsl
def noXmlOrXslFiles = Directories.listEntities(d, 
  EFileFilter.FILTER &
  ~(new EFileNameExtensionFilter('.xml') |
    new EFileNameExtensionFilter('.xsl')))

Grep with filters

Filter:s extending AbstractConvenientFilter can also be used with a collection's grep method to select the elements in the collection matching the filter.

Example 2. Using grep to select files in a collection

import org.entityfs.util.Directories
import org.entityfs.util.filter.entity.*

// List all files in the directory d
def files = Directories.listEntities(d)

// Use grep to return all XML files that contain the <foo> element.
def filter = new EFileNameExtensionFilter(".xml") &
  new FGrepFilter("<foo>")

// Get all XML files
def xmlFiles = files.grep(filter)

Filters in switch statements

Filters can be used in Groovy switch statements. In the example below, a switch statement is used with an entity filter to log different statements for directories that contain less than or exactly or more than four XML files.

Example 3. Searching for directories with more than four XML files

import org.entityfs.util.*
import org.entityfs.util.filter.entity.*

// For each directory in the directory hieararchy under d, test if it contains
// four or more XML files.

// A filter matching directories containing at least four XML files.
def fourXmlFilesFilter = new DirectoryContainsFilter(
  new EFileNameExtensionFilter("xml"), 4)

// Execute closure for all directories under d.
Directories.findEntities(d, DirectoryFilter.FILTER).each
{
  switch(it)
  {
    case fourXmlFilesFilter:
      println Entities.getName(it) + " contains four or more XML files"
      break

    default:
      println Entities.getName(it) + " contains less than four XML files"
  }
}