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.jdom;
17:
18: import java.util.List;
19:
20: import org.apache.commons.jxpath.AbstractFactory;
21: import org.apache.commons.jxpath.JXPathContext;
22: import org.apache.commons.jxpath.Pointer;
23: import org.jdom.Element;
24:
25: /**
26: * Test AbstractFactory.
27: *
28: * @author Dmitri Plotnikov
29: * @version $Revision: 1.6 $ $Date: 2004/06/29 22:58:17 $
30: */
31: public class TestJDOMFactory extends AbstractFactory {
32:
33: /**
34: * Create a new instance and put it in the collection on the parent object.
35: * Return <b>false</b> if this factory cannot create the requested object.
36: */
37: public boolean createObject(JXPathContext context, Pointer pointer,
38: Object parent, String name, int index) {
39: if (name.equals("location") || name.equals("address")
40: || name.equals("street")) {
41: addJDOMElement((Element) parent, index, name, null);
42: return true;
43: }
44: if (name.startsWith("price:")) {
45: String namespaceURI = context.getNamespaceURI("price");
46: addJDOMElement((Element) parent, index, name, namespaceURI);
47: return true;
48: }
49:
50: return false;
51: }
52:
53: private void addJDOMElement(Element parent, int index, String tag,
54: String namespaceURI) {
55: List children = parent.getContent();
56: int count = 0;
57: for (int i = 0; i < children.size(); i++) {
58: Object child = children.get(i);
59: if (child instanceof Element
60: && ((Element) child).getQualifiedName().equals(tag)) {
61: count++;
62: }
63: }
64:
65: // Keep inserting new elements until we have index + 1 of them
66: while (count <= index) {
67: // In a real factory we would need to do the right thing with
68: // the namespace prefix.
69: Element newElement;
70: if (namespaceURI != null) {
71: String prefix = tag.substring(0, tag.indexOf(':'));
72: tag = tag.substring(tag.indexOf(':') + 1);
73: newElement = new Element(tag, prefix, namespaceURI);
74: } else {
75: newElement = new Element(tag);
76: }
77: parent.addContent(newElement);
78: count++;
79: }
80: }
81:
82: public boolean declareVariable(JXPathContext context, String name) {
83: return false;
84: }
85: }
|