summaryrefslogtreecommitdiffstats
path: root/sca-java-1.x/branches/sca-java-integration/sca/kernel/core/src/main/java/org/apache/tuscany/core/property/PropertyHelper.java
blob: 36054dc2f657de11404276fa52be4e31bbd2ede5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */

package org.apache.tuscany.core.property;

import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.tuscany.core.databinding.xml.InputStream2Node;
import org.apache.tuscany.spi.databinding.extension.DOMHelper;
import org.apache.tuscany.spi.deployer.DeploymentContext;
import org.apache.tuscany.spi.loader.InvalidValueException;
import org.apache.tuscany.spi.loader.LoaderException;
import org.apache.tuscany.spi.model.ComponentDefinition;
import org.apache.tuscany.spi.model.CompositeComponentType;
import org.apache.tuscany.spi.model.Implementation;
import org.apache.tuscany.spi.model.Property;
import org.apache.tuscany.spi.model.PropertyValue;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
 * The property factory backed by the DataBindingframework
 */
public final class PropertyHelper {

    private static final XPathFactory FACTORY = XPathFactory.newInstance();

    private PropertyHelper() {
    }

    public static Document evaluate(NamespaceContext nsContext, Node node, String xPathExpression)
        throws XPathExpressionException, ParserConfigurationException {
        XPath path = FACTORY.newXPath();
        if (nsContext != null) {
            path.setNamespaceContext(nsContext);
        } else {
            path.setNamespaceContext(new DOMNamespeceContext(node));
        }
        XPathExpression expression = path.compile(xPathExpression);
        Node result = (Node)expression.evaluate(node, XPathConstants.NODE);
        if (result == null) {
            return null;
        }

        // TODO: How to wrap the result into a Document?
        Document document = DOMHelper.newDocument();
        if (result instanceof Document) {
            return (Document)result;
        } else {
            document.appendChild(document.importNode(result, true));
            return document;
        }
    }

    public static Document loadFromFile(String file, DeploymentContext deploymentContext)
        throws LoaderException {
        try {
            URI uri = URI.create(file);
            URL url = null;
            if (!uri.isAbsolute()) {
                url = deploymentContext.getClassLoader().getResource(file);
            } else {
                url = uri.toURL();
            }
            InputStream is = url.openStream();
            try {
                InputStream2Node transformer = new InputStream2Node();
                return (Document)transformer.transform(is, null);
            } finally {
                is.close();
            }
        } catch (Exception e) {
            throw new LoaderException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public static void processProperties(CompositeComponentType<?, ?, Property<?>> parent,
                                         ComponentDefinition<? extends Implementation<?>> componentDefinition,
                                         DeploymentContext deploymentContext) throws LoaderException {
        Map<String, PropertyValue<?>> propertyValues = componentDefinition.getPropertyValues();
        
        for (PropertyValue propValue : propertyValues.values()) {
            String source = propValue.getSource();
            String file = propValue.getFile();
            if (source != null) {
                try {
                    // $<name>/...
                    int index = source.indexOf('/');
                    if (index == -1) {
                        // Tolerating $prop
                        source = source + "/";
                        index = source.length() - 1;
                    }
                    if (source.charAt(0) == '$') {
                        String name = source.substring(1, index);
                        Property<?> compositeProp = parent.getProperties().get(name);
                        if (compositeProp == null) {
                            InvalidValueException ex =
                                new InvalidValueException(
                                                          "The 'source' cannot be resolved to a composite property");
                            ex.addContextName(source);
                            throw ex;
                        }
                        
                        boolean prependValue = false;
                        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                        Document compositePropDefValues = builder.newDocument();
                        Node element = null;
                        for (int count = 0 ; count < compositeProp.getDefaultValues().size() ; ++count) {
                        	element = compositeProp.getDefaultValues().get(count);
                            prependValue = element.getNodeName().equals("value");
                            element = compositePropDefValues.adoptNode(element);
                            compositePropDefValues.appendChild(element);
                        }
                        // Adding /value because the document root is "value"
                        String path = source.substring(index);
                        String xpath = null;
                        Property<?> componentProperty = (Property<?>) 
                            componentDefinition.getImplementation().getComponentType().getProperties().get(propValue.getName());
                        if (prependValue) {
                            if ("/".equals(path)) {
                                // trailing / is not legal for xpath
                                xpath = "/value";
                            } else {
                                xpath = "/value" + path;
                            }
                        } else {
                            xpath = path;
                        }
                            
                        // FIXME: How to deal with namespaces?
                        Document node = evaluate(null, compositePropDefValues, xpath);
                        //Document node = evaluate(null, compositeProp.getDefaultValues().get(0).getOwnerDocument(), xpath);
                        if (node != null) {
                            List<Document> values = new ArrayList<Document>();
                            values.add(node);
                            propValue.setValue(values);
                        } 
                    } else {
                        InvalidValueException ex =
                            new InvalidValueException("The 'source' has an invalid value");
                        ex.addContextName(source);
                        throw ex;
                    }
                } catch (Exception e) {
                    throw new LoaderException(e);
                }
            } else if (file != null) {
                Property<?> prop =
                    (Property<?>)componentDefinition.getImplementation().getComponentType().getProperties()
                        .get(propValue.getName());
                Document document = loadFromFile(propValue.getFile(), deploymentContext);
                List<Element> values = new ArrayList<Element>();
                if (prop.isMany()) {
                	//extract the property value elements from the loaded document
                	Element element = document.getDocumentElement();
                	Node childNode = null;
                	for (int count = 0 ; count < element.getChildNodes().getLength() ; ++count) {
                		if (element.getChildNodes().item(count).getNodeType() == Document.ELEMENT_NODE) {
                			values.add((Element)element.getChildNodes().item(count));
                		}
                	}
                	propValue.setValue(values);
                	propValue.setValueFactory(new SimpleMultivaluedPropertyObjectFactory(prop, propValue.getValue()));
                } else {
                	values.add(document.getDocumentElement());
                	propValue.setValue(values);
                	propValue.setValueFactory(new SimplePropertyObjectFactory(prop, (Element)propValue.getValue().get(0)));
                }
            }
        }
    }
    
    private static class DOMNamespeceContext implements NamespaceContext {
        private Node node;

        /**
         * @param node
         */
        public DOMNamespeceContext(Node node) {
            super();
            this.node = node;
        }

        public String getNamespaceURI(String prefix) {
            //return "http://foo";
            return node.lookupNamespaceURI(prefix);
        }

        public String getPrefix(String namespaceURI) {
            //return "foo";
            return node.lookupPrefix(namespaceURI);
        }

        public Iterator getPrefixes(String namespaceURI) {
            return null;
        }

    }

}