01: /*
02: * Copyright 1999-2004 The Apache Software Foundation
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.apache.commons.jxpath.ri.model.dom;
17:
18: import org.apache.commons.jxpath.AbstractFactory;
19: import org.apache.commons.jxpath.JXPathContext;
20: import org.apache.commons.jxpath.Pointer;
21: import org.w3c.dom.Document;
22: import org.w3c.dom.Node;
23:
24: /**
25: * Test AbstractFactory.
26: *
27: * @author Dmitri Plotnikov
28: * @version $Revision: 1.6 $ $Date: 2004/06/29 22:58:17 $
29: */
30: public class TestDOMFactory extends AbstractFactory {
31:
32: /**
33: * Return <b>false</b> if this factory cannot create the requested object.
34: */
35: public boolean createObject(JXPathContext context, Pointer pointer,
36: Object parent, String name, int index) {
37: if (name.equals("location") || name.equals("address")
38: || name.equals("street")) {
39: addDOMElement((Node) parent, index, name, null);
40: return true;
41: }
42: if (name.startsWith("price:")) {
43: String namespaceURI = context.getNamespaceURI("price");
44: addDOMElement((Node) parent, index, name, namespaceURI);
45: return true;
46: }
47: return false;
48: }
49:
50: private void addDOMElement(Node parent, int index, String tag,
51: String namespaceURI) {
52: Node child = parent.getFirstChild();
53: int count = 0;
54: while (child != null) {
55: if (child.getNodeName().equals(tag)) {
56: count++;
57: }
58: child = child.getNextSibling();
59: }
60:
61: // Keep inserting new elements until we have index + 1 of them
62: while (count <= index) {
63: Document doc = parent.getOwnerDocument();
64: Node newElement;
65: if (namespaceURI == null) {
66: newElement = doc.createElement(tag);
67: } else {
68: newElement = doc.createElementNS(namespaceURI, tag);
69: }
70:
71: parent.appendChild(newElement);
72: count++;
73: }
74: }
75:
76: public boolean declareVariable(JXPathContext context, String name) {
77: return false;
78: }
79: }
|