1//
2//  ========================================================================
3//  Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
4//  ------------------------------------------------------------------------
5//  All rights reserved. This program and the accompanying materials
6//  are made available under the terms of the Eclipse Public License v1.0
7//  and Apache License v2.0 which accompanies this distribution.
8//
9//      The Eclipse Public License is available at
10//      http://www.eclipse.org/legal/epl-v10.html
11//
12//      The Apache License v2.0 is available at
13//      http://www.opensource.org/licenses/apache2.0.php
14//
15//  You may elect to redistribute this code under either of these licenses.
16//  ========================================================================
17//
18
19package org.eclipse.jetty.webapp;
20
21import java.lang.reflect.Method;
22import java.util.HashMap;
23import java.util.Iterator;
24import java.util.Map;
25
26import org.eclipse.jetty.xml.XmlParser;
27
28/**
29 * IterativeDescriptorProcessor
30 *
31 *
32 */
33public abstract class IterativeDescriptorProcessor implements DescriptorProcessor
34{
35    public static final Class<?>[] __signature = new Class[]{WebAppContext.class, Descriptor.class, XmlParser.Node.class};
36    protected Map<String, Method> _visitors = new HashMap<String, Method>();
37    public abstract void start(WebAppContext context, Descriptor descriptor);
38    public abstract void end(WebAppContext context, Descriptor descriptor);
39
40    /**
41     * Register a method to be called back when visiting the node with the given name.
42     * The method must exist on a subclass of this class, and must have the signature:
43     * public void method (Descriptor descriptor, XmlParser.Node node)
44     * @param nodeName
45     * @param m
46     */
47    public void registerVisitor(String nodeName, Method m)
48    {
49        _visitors.put(nodeName, m);
50    }
51
52
53    /**
54     * {@inheritDoc}
55     */
56    public void process(WebAppContext context, Descriptor descriptor)
57    throws Exception
58    {
59        if (descriptor == null)
60            return;
61
62        start(context,descriptor);
63
64        XmlParser.Node root = descriptor.getRoot();
65        Iterator<?> iter = root.iterator();
66        XmlParser.Node node = null;
67        while (iter.hasNext())
68        {
69            Object o = iter.next();
70            if (!(o instanceof XmlParser.Node)) continue;
71            node = (XmlParser.Node) o;
72            visit(context, descriptor, node);
73        }
74
75        end(context,descriptor);
76    }
77
78
79    protected void visit (WebAppContext context, Descriptor descriptor, XmlParser.Node node)
80    throws Exception
81    {
82        String name = node.getTag();
83        Method m =  _visitors.get(name);
84        if (m != null)
85            m.invoke(this, new Object[]{context, descriptor, node});
86    }
87}
88