Questo contenuto non è disponibile nella lingua selezionata.

3.19. Using an MVEL Expression


  1. To use an MVEL expression on a rule set, divide the Regex rules and place them in two separate .properties files.
  2. Drop these rules into the example rules directory.
  3. Put the MVEL expression in a .csv file, also in the rules directory.
    The customer-related Regex rules that go in the customer.properties file look like this:
    # Customer data rules...
    customerId=[A-Z][0-9]{5}
     
    # Email address...
    email=^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$
    
    Copy to Clipboard Toggle word wrap
  4. Insert the product-related Regex rule in the product.properties file:
    # Product data rules...
    productId=[0-9]{3}
    
    Copy to Clipboard Toggle word wrap
  5. Insert the MVEL expression for performing the order item total check into the order-rules.csv file.
    Note
    The easiest way to edit a .csv file is through using a spreadsheet application like LibreOffice Calc or Gnumeric.
  6. Create resource bundle .properties files for each of the rule source files.
    Note
    The names of these files are derived from the names of their corresponding rule files.
    The message bundle for the rules defined in rules/customer.properties is located in the rules/i18n/customer.properties file:
    customerId=ftl:Invalid customer number '${ruleResult.text}' at '${path}'. Customer number must begin with an uppercase character, followed by 5 digits. 
    email=ftl:Invalid email address '${ruleResult.text}' at '${path}'. Email addresses match pattern '${ruleResult.pattern}'.
    Copy to Clipboard Toggle word wrap
    The message bundle for the rule defined in rules/product.properties is located in the rules/i18n/product.properties file:
    # Product data rule messages...
    productId=ftl:Invalid product ID '${ruleResult.text}' at '${path}'. Product ID must match pattern '${ruleResult.pattern}'.
    Copy to Clipboard Toggle word wrap
    The message bundle for the rule defined in rules/order-rules.csv is located in the rules/i18n/order-rules.properties file:
    # Order item rule messages. The "orderDetails" and "orderItem" beans are populated by Smooks bindings
    order_item_total=ftl:Order ${orderDetails.orderId} contains an order item for product ${orderItem.productId} with a quantity of ${orderItem.quantity} and a unit price of ${orderItem.price}. This exceeds the permitted per order item total.
    Copy to Clipboard Toggle word wrap
  7. Apply this validation to the rules:
    <?xml version="1.0"?>
    <smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
                          xmlns:rules="http://www.milyn.org/xsd/smooks/rules-1.0.xsd"
                          xmlns:validation="http://www.milyn.org/xsd/smooks/validation-1.0.xsd"
                          xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.2.xsd">
     
        <params>
            <!-- Generate a ValidationException if we get more than 5 validation failures... -->
            <param name="validation.maxFails">5</param>
        </params>
     
        <!-- Define the ruleBases that are used by the validation rules... -->
        <rules:ruleBases>
            <!-- Field value rules using regex... -->
            <rules:ruleBase name="customer" src="rules/customer.properties" provider="org.milyn.rules.regex.RegexProvider"/>
            <rules:ruleBase name="product" src="rules/product.properties" provider="org.milyn.rules.regex.RegexProvider"/>
     
            <!-- Order business rules using MVEL expressions... -->
            <rules:ruleBase name="order" src="rules/order-rules.csv" provider="org.milyn.rules.mvel.MVELProvider"/>
        </rules:ruleBases>
     
        <!-- Capture some data into the bean context - required by the business rule validations... -->
        <jb:bean beanId="orderDetails" class="java.util.HashMap" createOnElement="header">
            <jb:value data="header/*"/>
        </jb:bean>
        <jb:bean beanId="orderItem" class="java.util.HashMap" createOnElement="order-item">
            <jb:value data="order-item/*"/>
        </jb:bean>
     
        <!-- Target validation rules... -->
        <validation:rule executeOn="header/username" name="customer.customerId" onFail="ERROR"/>
        <validation:rule executeOn="email" name="customer.email" onFail="WARN"/>
        <validation:rule executeOn="order-item/productId" name="product.productId" onFail="ERROR"/>
     
        <validation:rule executeOn="order-item" name="order.order_item_total" onFail="ERROR"/>
     
    </smooks-resource-list>
    Copy to Clipboard Toggle word wrap
  8. Execute from the example's Main class using this code:
    protected static ValidationResult runSmooks(final String messageIn) throws IOException, SAXException, SmooksException {
        // Instantiate Smooks with the config...
        final Smooks smooks = new Smooks("smooks-config.xml");
     
        try {
            // Create an exec context - no profiles....
            final ExecutionContext executionContext = smooks.createExecutionContext();
            final ValidationResult validationResult = new ValidationResult();
     
            // Configure the execution context to generate a report...
            executionContext.setEventListener(new HtmlReportGenerator("target/report/report.html"));
     
            // Filter the input message...
            smooks.filterSource(executionContext, new StringSource(messageIn), validationResult);
     
            return validationResult;
        }
        finally {
            smooks.close();
        }
    }
    Copy to Clipboard Toggle word wrap
Torna in cima
Red Hat logoGithubredditYoutubeTwitter

Formazione

Prova, acquista e vendi

Community

Informazioni sulla documentazione di Red Hat

Aiutiamo gli utenti Red Hat a innovarsi e raggiungere i propri obiettivi con i nostri prodotti e servizi grazie a contenuti di cui possono fidarsi. Esplora i nostri ultimi aggiornamenti.

Rendiamo l’open source più inclusivo

Red Hat si impegna a sostituire il linguaggio problematico nel codice, nella documentazione e nelle proprietà web. Per maggiori dettagli, visita il Blog di Red Hat.

Informazioni su Red Hat

Forniamo soluzioni consolidate che rendono più semplice per le aziende lavorare su piattaforme e ambienti diversi, dal datacenter centrale all'edge della rete.

Theme

© 2025 Red Hat