001    /******************************************************************************
002     * Copyright (C) MActor Developers. All rights reserved.                        *
003     * ---------------------------------------------------------------------------*
004     * This file is part of MActor.                                               *
005     *                                                                            *
006     * MActor is free software; you can redistribute it and/or modify             *
007     * it under the terms of the GNU General Public License as published by       *
008     * the Free Software Foundation; either version 2 of the License, or          *
009     * (at your option) any later version.                                        *
010     *                                                                            *
011     * MActor is distributed in the hope that it will be useful,                  *
012     * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
013     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
014     * GNU General Public License for more details.                               *
015     *                                                                            *
016     * You should have received a copy of the GNU General Public License          *
017     * along with MActor; if not, write to the Free Software                      *
018     * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA *
019     ******************************************************************************/
020    package org.mactor.extensions.xml;
021    
022    import java.io.File;
023    import java.util.HashMap;
024    import java.util.Iterator;
025    import java.util.List;
026    import java.util.Map;
027    import java.util.Map.Entry;
028    
029    import org.dom4j.Document;
030    import org.dom4j.DocumentException;
031    import org.dom4j.Element;
032    import org.dom4j.Namespace;
033    import org.dom4j.Node;
034    import org.dom4j.XPath;
035    import org.dom4j.io.SAXReader;
036    import org.mactor.brokers.Message;
037    import org.mactor.framework.ConfigException;
038    import org.mactor.framework.MactorException;
039    import org.mactor.framework.TestContext;
040    import org.mactor.framework.extensioninterface.MessageBuilderCommand;
041    
042    /**
043     * Builds a message based on a XML file (the template), substituting the vales
044     * in the file with the values specied in the paramaters.<br/>
045     * 
046     * The syntax of a parameters are:<br>
047     * [XPath expression that selects the single attribute or element ]==[value that
048     * should be assigned to the field] <br/> If the namespace prefixes are used in
049     * the template file, the same prefixes must be used in the XPath expression.<br/>
050     * If the a default namespace is used in the template file, 'def' must by used a
051     * namespace prefix in the XPath expression<br/>
052     * 
053     * @author Lars Ivar Almli
054     */
055    public class XPathTemplateMessageBuilder implements MessageBuilderCommand {
056            public Message buildMessage(TestContext context, String templatePath, List<String> params) throws MactorException {
057                    // long start = System.currentTimeMillis();
058                    File template = new File(templatePath);
059                    if (!template.exists())
060                            throw new MactorException("The specified template '" + template.getAbsolutePath() + "' does not exist");
061                    Document doc = null;
062                    try {
063                            doc = new SAXReader().read(template);
064                    } catch (DocumentException de) {
065                            throw new MactorException("Failed to parse template '" + template.getAbsolutePath() + "' as xml");
066                    }
067                    HashMap<XPath, String> map = ParamUtil.parseXPathParams(params);
068                    Map nsMap = new HashMap();
069                    findNameSpaces(nsMap, doc.getRootElement());
070                    for (Entry<XPath, String> e : map.entrySet()) {
071                            e.getKey().setNamespaceURIs(nsMap);
072                    }
073                    for (Entry<XPath, String> e : map.entrySet()) {
074                            Node n = e.getKey().selectSingleNode(doc);
075                            if (n == null)
076                                    throw new ConfigException("The template '" + templatePath + "' does not contain the xpath '" + e.getKey() + "'");
077                            n.setText(e.getValue());
078                    }
079                    return Message.createMessage(doc);
080            }
081            private void addNsPrefix(Map m, String prefix, String uri) throws ConfigException {
082                    if (m.containsKey(prefix)) {
083                            if (!uri.equals(m.get(prefix)))
084                                    throw new ConfigException("Namespace conflict. The namespace '" + prefix + "' is used for both '" + uri + "' and '" + m.get(prefix) + "'");
085                    } else
086                            m.put(prefix, uri);
087            }
088            private void findNameSpaces(Map nsMap, Element element) throws ConfigException {
089                    List nsList = element.declaredNamespaces();
090                    for (Object o : nsList) {
091                            Namespace ns = (Namespace) o;
092                            // Ok, this is a hack to simplify the XPathTemplateMessageBuilder
093                            // 'user
094                            // interface': use 'def' as the default prefix
095                            if (ns.getPrefix() == null || ns.getPrefix().length() == 0)
096                                    addNsPrefix(nsMap, "def", ns.getURI());
097                            else
098                                    addNsPrefix(nsMap, ns.getPrefix(), ns.getURI());
099                    }
100                    Iterator it = element.elementIterator();
101                    while (it.hasNext())
102                            findNameSpaces(nsMap, (Element) it.next());
103            }
104    }