summaryrefslogtreecommitdiff
path: root/src/main/java/com/c2kernel/persistency/outcome/Outcome.java
blob: 70a2a24c3929101c197655d358d69c56dd3dd29a (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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package com.c2kernel.persistency.outcome;
import java.io.StringReader;
import java.util.StringTokenizer;

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.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;

import com.c2kernel.common.InvalidDataException;
import com.c2kernel.common.ObjectNotFoundException;
import com.c2kernel.common.PersistencyException;
import com.c2kernel.entity.C2KLocalObject;
import com.c2kernel.persistency.ClusterStorage;
import com.c2kernel.utils.LocalObjectLoader;
import com.c2kernel.utils.Logger;

public class Outcome implements C2KLocalObject {
    Integer mID;
    String mData;
    String mSchemaType;
    int mSchemaVersion;
    Document dom;
    static DocumentBuilder parser;
    static DOMImplementationLS impl;
    static XPath xpath;

    static {
    	// Set up parser
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        dbf.setNamespaceAware(false);
        try {
            parser = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            Logger.error(e);
            Logger.die("Cannot function without XML parser");
        }

        // Set up serialiser
        try {
			DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
	    	impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
		} catch (Exception e) {
            Logger.error(e);
            Logger.die("Cannot function without XML serialiser");
		}
        
        XPathFactory xPathFactory = XPathFactory.newInstance();
        xpath = xPathFactory.newXPath();
    }

    //id is the eventID
    public Outcome(int id, String data, String schemaType, int schemaVersion) {
        mID = id;
        mData = data;
        mSchemaType = schemaType;
        mSchemaVersion = schemaVersion;
    }

    public Outcome(String path, String data) throws PersistencyException {
    // derive all the meta data from the path
        StringTokenizer tok = new StringTokenizer(path,"/");
        if (tok.countTokens() != 3 && !(tok.nextToken().equals(ClusterStorage.OUTCOME)))
            throw new PersistencyException("Outcome() - Outcome path must have three components: "+path, null);
        mSchemaType = tok.nextToken();
        String verstring = tok.nextToken();
        String objId = tok.nextToken();
        try {
            mSchemaVersion = Integer.parseInt(verstring);
        } catch (NumberFormatException ex) {
            throw new PersistencyException("Outcome() - Outcome version was an invalid number: "+verstring, null);
        }
        try {
            mID = new Integer(objId);
        } catch (NumberFormatException ex) {
            mID = null;
        }
        mData = data;
    }

    public void setID(Integer ID) {
        mID = ID;
    }

    public Integer getID() {
        return mID;
    }

    @Override
	public void setName(String name) {
    	try {
    		mID = new Integer(name);
    	} catch (NumberFormatException e) {
    		Logger.error("Invalid id set on Outcome:"+name);
    	}
    }

    @Override
	public String getName() {
        return mID.toString();
    }

    public void setData(String data) {
        mData = data;
        dom = null;
    }

    public void setData(Document data) {
        dom = data;
        mData = null;
    }
    
    public String getFieldByXPath(String xpath) throws XPathExpressionException, InvalidDataException {
    	Node field = getNodeByXPath(xpath);
    	if (field == null)
    		throw new InvalidDataException(xpath, "");
    	
    	else if (field.getNodeType()==Node.TEXT_NODE || field.getNodeType()==Node.CDATA_SECTION_NODE)
    		return field.getNodeValue();
    	
    	else if (field.getNodeType()==Node.ELEMENT_NODE) {
    		NodeList fieldChildren = field.getChildNodes();
    		if (fieldChildren.getLength() == 0) 
    			throw new InvalidDataException("No child node for element", "");
    		
    		else if (fieldChildren.getLength() == 1) {
    			Node child = fieldChildren.item(0);
    			if (child.getNodeType()==Node.TEXT_NODE || child.getNodeType()==Node.CDATA_SECTION_NODE)
    				return child.getNodeValue();
    			else
    				throw new InvalidDataException("Can't get data from child node of type "+child.getNodeName(), "");
    		}
    		else 
    			throw new InvalidDataException("Element "+xpath+" has too many children", "");
    	}
    	else if (field.getNodeType()==Node.ATTRIBUTE_NODE)		
    		return field.getNodeValue();
    	else
    		throw new InvalidDataException("Don't know what to do with node "+field.getNodeName(), "");
    }
    
    public void setFieldByXPath(String xpath, String data) throws XPathExpressionException, InvalidDataException {
    	Node field = getNodeByXPath(xpath);
    	if (field == null)
    		throw new InvalidDataException(xpath, "");

    	else if (field.getNodeType()==Node.ELEMENT_NODE) {
    		NodeList fieldChildren = field.getChildNodes();
    		if (fieldChildren.getLength() == 0) {
    			field.appendChild(dom.createTextNode(data));
    		}
    		else if (fieldChildren.getLength() == 1) {
    			Node child = fieldChildren.item(0);
    			switch (child.getNodeType()) {
    			case Node.TEXT_NODE:
    			case Node.CDATA_SECTION_NODE:
    				child.setNodeValue(data);
    				break;
    			default:
    				throw new InvalidDataException("Can't set child node of type "+child.getNodeName(), "");
    			}
    		}
    		else 
    			throw new InvalidDataException("Element "+xpath+" has too many children", "");
    	}
    	else if (field.getNodeType()==Node.ATTRIBUTE_NODE)		
    		field.setNodeValue(data);
    	else
    		throw new InvalidDataException("Don't know what to do with node "+field.getNodeName(), "");
    }


    public String getData() {
    	if (mData == null && dom != null) {
    		mData = serialize(dom, false);
    	}
        return mData;
    }

    public Schema getSchema() throws ObjectNotFoundException {
    	return LocalObjectLoader.getSchema(mSchemaType, mSchemaVersion);
    }
    
    public void setSchemaType(String schemaType) {
        mSchemaType = schemaType;
    }

    public String getSchemaType() {
        return mSchemaType;
    }

    public int getSchemaVersion() {
        return mSchemaVersion;
    }

    public void setSchemaVersion(int schVer) {
        mSchemaVersion = schVer;
    }

	@Override
	public String getClusterType() {
		return ClusterStorage.OUTCOME;
	}

    // special script API methods

    /**
     * Parses the outcome into a DOM tree
     * @return a DOM Document
     */
    public Document getDOM() {
    	if (dom == null)
        try {
            synchronized (parser) {
            	if (mData!=null)
            		dom = parser.parse(new InputSource(new StringReader(mData)));
            	else
            		dom = parser.newDocument();
            }
        } catch (Exception e) {
            Logger.error(e);
            return null;
        }
    	return dom;
    }
    
    public String getField(String name) {
    	 NodeList elements = getDOM().getDocumentElement().getElementsByTagName(name);
    	 if (elements.getLength() == 1 && elements.item(0).hasChildNodes() && elements.item(0).getFirstChild() instanceof Text)
    		 return ((Text)elements.item(0).getFirstChild()).getData();
    	 else
    		 return null;
    }
    
    public NodeList getNodesByXPath(String xpathExpr) throws XPathExpressionException {
    	
    	XPathExpression expr = xpath.compile(xpathExpr);
    	return (NodeList)expr.evaluate(getDOM(), XPathConstants.NODESET);
    	
    }
    
    public Node getNodeByXPath(String xpathExpr) throws XPathExpressionException {
    	
    	XPathExpression expr = xpath.compile(xpathExpr);
    	return (Node)expr.evaluate(getDOM(), XPathConstants.NODE);
    	
    }

    static public String serialize(Document doc, boolean prettyPrint)
    {
    	LSSerializer writer = impl.createLSSerializer();
    	writer.getDomConfig().setParameter("format-pretty-print", prettyPrint);
    	writer.getDomConfig().setParameter("xml-declaration", false);
    	return writer.writeToString(doc);
    }
}