summaryrefslogtreecommitdiff
path: root/src/main/java/com/c2kernel/process/module/Module.java
blob: 22f4543016db50fc9018becc56584e7b6ac2fff4 (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
package com.c2kernel.process.module;

import java.io.StringReader;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;

import com.c2kernel.common.CannotManageException;
import com.c2kernel.common.ObjectAlreadyExistsException;
import com.c2kernel.common.ObjectCannotBeUpdated;
import com.c2kernel.common.ObjectNotFoundException;
import com.c2kernel.entity.proxy.ItemProxy;
import com.c2kernel.lifecycle.instance.predefined.entitycreation.NewAgent;
import com.c2kernel.lifecycle.instance.predefined.entitycreation.NewItem;
import com.c2kernel.lookup.DomainPath;
import com.c2kernel.process.Bootstrap;
import com.c2kernel.process.Gateway;
import com.c2kernel.scripting.ErrorInfo;
import com.c2kernel.scripting.ScriptingEngineException;
import com.c2kernel.utils.Logger;
import com.c2kernel.utils.Resource;

public class Module {

	public String ns, name;
	public ModuleInfo info;
	public String resURL;
	public ModuleImports imports = new ModuleImports();
	public ArrayList<ModuleConfig> config = new ArrayList<ModuleConfig>();
	public ArrayList<ModuleScript> scripts = new ArrayList<ModuleScript>();
	private static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	private DocumentBuilder parser;
	private Document moduleDOM;
    
	static {
        dbf.setValidating(false);
        dbf.setNamespaceAware(false);
	}
	
	public Module() {
		super();
	}
	
	public Module(String moduleXML) throws ModuleException {
		try {
			parser = dbf.newDocumentBuilder();
			moduleDOM = parser.parse(new InputSource(new StringReader(moduleXML)));
		} catch (Exception e) {
			Logger.error(e);
			throw new ModuleException("Could not process modules. XML Parser exception");
		}
		
        Element root = (Element)moduleDOM.getElementsByTagName("CristalModule").item(0);
        
        // Get module metadata
        ns = root.getAttribute("ns");
        name = root.getAttribute("name");
        
        Element infoElem = (Element)moduleDOM.getElementsByTagName("Info").item(0);
        info = new ModuleInfo();
        info.desc = ((Text)infoElem.getElementsByTagName("Description").item(0).getFirstChild()).getData();
        info.version = ((Text)infoElem.getElementsByTagName("Version").item(0).getFirstChild()).getData();
        NodeList nl = infoElem.getElementsByTagName("Dependency");
        for (int i=0; i<nl.getLength();i++)
        	info.dependency.add(((Text)nl.item(i).getFirstChild()).getData());
        
        // register resource URL
        nl = root.getElementsByTagName("ResourceURL");
        if (nl.getLength()>0) {
        	resURL = ((Text)nl.item(0).getFirstChild()).getData();
            Resource.addModuleBaseURL(ns, resURL);
        }
        
        // Get config properties
        nl = root.getElementsByTagName("Config");
        for (int i=0; i<nl.getLength();i++) {
        	Element confElement = (Element)nl.item(i);
        	String target = confElement.getAttribute("target");
        	String name = confElement.getAttribute("name");
        	String value = ((Text)confElement.getFirstChild()).getData();
        	config.add(new ModuleConfig(name, value, target));
        }
        
        // find scripts
        nl = root.getElementsByTagName("Script");
        for (int i=0; i<nl.getLength();i++) {
        	Element confElement = (Element)nl.item(i);
        	String target = confElement.getAttribute("target");
        	String event = confElement.getAttribute("event");
        	String lang = confElement.getAttribute("lang");
        	scripts.add(new ModuleScript(target, event, lang, ((Text)confElement.getFirstChild()).getData()));
        }
        
        // Get imports
        nl = moduleDOM.getElementsByTagName("Imports");
        if (nl.getLength()>0) {
	        Element impElem = (Element)nl.item(0);
	        nl = impElem.getChildNodes();
	        for (int i=0; i<nl.getLength();i++) {
	        	if (!(nl.item(i) instanceof Element)) continue;
	        	Element imp = (Element)nl.item(i);
	        	ModuleImport newImp;
	        	String type = imp.getTagName();
	        	if (type.equals("Resource")) {
	        		ModuleResource newRes = new ModuleResource(imp); 
	        		newImp = newRes;
	        	}
	        	else if (type.equals("Item")) {
	        		NewItem newItem = new NewItem(ns, imp); 
	        		newImp = newItem;
	        	}
	        	else if (type.equals("Agent")) {
	        		NewAgent newAgent = new NewAgent(imp); 
	        		newImp = newAgent;
        		}
	        	else {
	        		Logger.warning("Unknown import type "+type);
	        		continue;
	        	}
	
	        	newImp.name = imp.getAttribute("name");
	        	imports.list.add(newImp);
	        	Logger.msg(8, "Found import "+imports.list.size()+"- "+newImp.name+": "+newImp.getClass().getSimpleName());
	        	
	        }
        }
        
	}
	
	public static com.c2kernel.property.Property newProperty(Element p) {
			return new com.c2kernel.property.Property(p.getAttribute("name"), ((Text)p.getFirstChild()).getData());
	}
	
	public void runScript(String event, boolean isServer) throws ScriptingEngineException {
		for (ModuleScript script : scripts) {
			if (script.shouldRun(event, isServer)) {
				Object result = script.getScript().execute();
				if (result instanceof ErrorInfo) {
					ErrorInfo error = (ErrorInfo) result;
					Logger.error(error.getErrors());
					if (error.getFatal())
						throw new ScriptingEngineException("Fatal Script Error");
				}
				else if (result != null)
					Logger.msg(result.toString());
			}
		}
	}
	
	public void importAll(ItemProxy serverEntity) throws ObjectCannotBeUpdated, ObjectNotFoundException, CannotManageException, ObjectAlreadyExistsException, NoSuchAlgorithmException {
		for (ModuleImport thisImp : imports.list) {
			Logger.msg(5, "Importing "+thisImp.name+" "+thisImp.getClass().getSimpleName());
			if (thisImp instanceof ModuleResource) {
				ModuleResource thisRes = (ModuleResource)thisImp;
				try {
					Bootstrap.verifyResource(ns, thisRes.name, thisRes.resourceType, Resource.getTextResource(ns, thisRes.resourceLocation));
				} catch (Exception ex) {
					Logger.error(ex);
				}
			}
			else if (thisImp instanceof NewItem) {
				NewItem thisItem = (NewItem)thisImp;
				thisItem.ns=ns;
				try {
					new DomainPath(new DomainPath(thisItem.initialPath), thisItem.name).getEntity();
				    Logger.msg(3, "Module.importAll() - Item '"+thisItem.name+"' found.");
				    continue;
				 } catch (ObjectNotFoundException ex) { }
				thisItem.create(Gateway.getLDAPLookup().getRoleManager().getAgentPath("system").getSysKey());
			}
			else if (thisImp instanceof NewAgent) {
				NewAgent thisAgent = (NewAgent)thisImp;
				try {
					Gateway.getLDAPLookup().getRoleManager().getAgentPath(thisAgent.name);
				    Logger.msg(3, "Module.importAll() - User '"+thisAgent.name+"' found.");
				    continue;
				 } catch (ObjectNotFoundException ex) { }
				 Logger.msg("Module.importAll() - User '"+thisAgent.name+"' not found. Creating.");

				thisAgent.create(Gateway.getLDAPLookup().getRoleManager().getAgentPath("system").getSysKey());
			}
		}
	}
	
	public Properties getProperties(boolean isServer) {
		Properties props = new Properties();
		for (ModuleConfig thisProp : config) {
			if (thisProp.include(isServer))
				props.put(thisProp.name, thisProp.value);
		}
		return props;
	}
	
	public String getNs() {
		return ns;
	}
	public String getName() {
		return name;
	}
	public String getDesc() {
		return info.desc;
	}
	public String getVersion() {
		return info.version;
	}
	public String getResURL() {
		return resURL;
	}
	public ArrayList<String> getDependencies() {
		return info.dependency;
	}
	public boolean hasDependency(String dep) {
		return info.dependency.contains(dep);
	}
}