001/* $Id: TestRecursion.java 1102402 2011-05-12 18:03:26Z simonetripodi $ 002 * 003 * Licensed to the Apache Software Foundation (ASF) under one or more 004 * contributor license agreements. See the NOTICE file distributed with 005 * this work for additional information regarding copyright ownership. 006 * The ASF licenses this file to You under the Apache License, Version 2.0 007 * (the "License"); you may not use this file except in compliance with 008 * the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018 019package org.apache.commons.digester3.plugins; 020 021import static org.junit.Assert.*; 022 023import java.util.List; 024 025import org.apache.commons.digester3.Digester; 026import org.apache.commons.digester3.plugins.PluginCreateRule; 027import org.apache.commons.digester3.plugins.PluginDeclarationRule; 028import org.apache.commons.digester3.plugins.PluginRules; 029import org.junit.Test; 030 031/** 032 * Test cases for plugins with custom rules which include PluginCreateRule instances, allowing recursive datastructures 033 * to be processed. 034 */ 035 036public class TestRecursion 037{ 038 039 // --------------------------------------------------------------- Test cases 040 @Test 041 public void testRecursiveRules() 042 throws Exception 043 { 044 // * tests that a rule can declare custom PluginCreateRules 045 // that allow it to plug in instances of itself below 046 // itself. 047 048 Digester digester = new Digester(); 049 PluginRules rc = new PluginRules(); 050 digester.setRules( rc ); 051 052 PluginDeclarationRule pdr = new PluginDeclarationRule(); 053 digester.addRule( "*/plugin", pdr ); 054 055 PluginCreateRule pcr = new PluginCreateRule( Widget.class ); 056 digester.addRule( "root/widget", pcr ); 057 digester.addSetNext( "root/widget", "addChild" ); 058 059 Container root = new Container(); 060 digester.push( root ); 061 062 try 063 { 064 digester.parse( Utils.getInputStream( this, "test6.xml" ) ); 065 } 066 catch ( Exception e ) 067 { 068 throw e; 069 } 070 071 int nDescendants = countWidgets( root ); 072 assertEquals( 10, nDescendants ); 073 } 074 075 private int countWidgets( Container c ) 076 { 077 List<Widget> l = c.getChildren(); 078 int sum = 0; 079 for ( Widget w : l ) 080 { 081 ++sum; 082 if ( w instanceof Container ) 083 { 084 sum += countWidgets( (Container) w ); 085 } 086 } 087 return sum; 088 } 089}