initial load
[DTRules.git] / DTRules / src / main / java / com / dtrules / admin / RulesAdminService.java
blob379c8241f57551da65fce6c28c480be510eba323
1 /*
2 * Copyright 2004-2007 MTBJ, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
16 package com.dtrules.admin;
18 import java.io.FileNotFoundException;
19 import java.io.FileOutputStream;
20 import java.io.OutputStream;
21 import java.io.PrintStream;
22 import java.util.ArrayList;
23 import java.util.Iterator;
24 import java.util.List;
26 import com.dtrules.decisiontables.RDecisionTable;
27 import com.dtrules.entity.IREntity;
28 import com.dtrules.entity.REntity;
29 import com.dtrules.entity.REntityEntry;
30 import com.dtrules.infrastructure.RulesException;
31 import com.dtrules.interpreter.IRObject;
32 import com.dtrules.interpreter.RName;
33 import com.dtrules.session.EntityFactory;
34 import com.dtrules.session.RSession;
35 import com.dtrules.session.RuleSet;
36 import com.dtrules.session.RulesDirectory;
38 /**
39 * @author Prasath Ramachandran
40 * Feb 1, 2007
42 * The RulesAdminService provides all the methods for adding to and maintaining a
43 * Rules in DTRules. This is the interface to be used by editors and other tools
44 * to add/remove decision tables, modify the Entity Description Dictionary, and
45 * create and modify Rule Sets.
47 @SuppressWarnings("unchecked")
48 public class RulesAdminService implements IRulesAdminService{
49 final private RSession session;
50 private RulesDirectory rd; // The Rules Directory provides a place where Rule
51 // sets are defined.
53 /**
54 * The RulesAdminService needs a session for specifing the output of debugging
55 * and trace information. It needs a Rules Directory to administer.
57 public RulesAdminService(final RSession session, final RulesDirectory rd) {
58 super();
59 this.session = session;
60 this.rd = rd;
63 /**
64 * Create a new Attribute; The Entity modified is specified by the attribute.
65 * @param rulesetname The name of the RuleSet where the attribute should be created.
66 * @param attribute The REntityEntry defines the Entity to be modified. It is
67 * assumed that this Entity already exists.
68 * @return true if the attribute was successfully added.
70 public boolean createAttribute(final String rulesetname, final REntityEntry attribute) {
71 try {
72 RuleSet rs = getRuleset(rulesetname);
73 IREntity entity = rs.getEntityFactory(session).findRefEntity(attribute.attribute);
74 entity.addAttribute(attribute);
75 return true;
76 } catch (RulesException e) {
77 return false;
82 /**
83 * Given a Rule Set and an Entity, returns the list of EntityEntry objects
84 * that define the meta information about each attribute of the entity. If an
85 * error occurs while building the list, an empty list is returned.
87 * @param rulesetname The Rule Set in which the entity is defined
88 * @param entityname The entity name of intrest.
89 * @return The list of Entity Entries that define the attributes of the Entity
91 public List<REntityEntry> getEntityEntries(String rulesetname, String entityname){
92 ArrayList<REntityEntry> entries = new ArrayList<REntityEntry>();
93 RuleSet rs = getRuleset(rulesetname);
94 IREntity entity;
95 try {
96 entity = rs.getEntityFactory(session).findRefEntity(RName.getRName(entityname));
97 Iterator<RName> attribs = entity.getAttributeIterator();
99 while(attribs.hasNext()){
100 entries.add(entity.getEntry(attribs.next()));
102 } catch (RulesException e) { }
104 return entries;
108 * Create a new Decision Table
110 public RDecisionTable createDecisionTable(String rulesetname, String decisiontablename)
111 throws RulesException{
112 RuleSet rs = getRuleset(rulesetname);
113 return rs.getEntityFactory(session).newDecisionTable(decisiontablename,session);
117 * Creates a new Entity of the given name within the RuleSet. If
118 * the Entity already exists or the name is invalid, or this operation
119 * fails in any other way, a null is returned.
120 * @see com.dtrules.admin.IRulesAdminService#createEntity(java.lang.String, java.lang.String)
121 * @param rulesetname The name of the RuleSet in which to create this entity
122 * @param EntityName The name of the new Entity
124 public IREntity createEntity(String rulesetname, boolean readonly, String entityName) {
125 RName name = RName.getRName(entityName);
126 IREntity e = session.getEntityFactory().findRefEntity(name);
127 if(e!=null)return null;
128 try {
129 return session.getEntityFactory().findcreateRefEntity(readonly, name);
130 } catch (RulesException e1) {
131 return null;
136 * Create a new Rule Set
137 * @see com.dtrules.admin.IRulesAdminService#createRuleset(com.dtrules.session.RuleSet)
139 public void createRuleset(RuleSet ruleset) throws RulesException{
140 rd.addRuleSet(ruleset);
143 /* (non-Javadoc)
144 * @see com.dtrules.admin.IRulesAdminService#getAttributes(java.lang.String, java.lang.String)
146 @SuppressWarnings("unchecked")
147 public List getAttributes(String rulesetname, String entityName) {
148 if(rd==null)return null;
149 try {
150 RuleSet rs = rd.getRuleSet(RName.getRName(rulesetname));
151 Iterator it = rs.getEntityFactory(session)
152 .findRefEntity(RName.getRName(entityName)).getAttributeIterator();
153 return getList(it);
154 } catch (RulesException e) {
155 return null;
159 /* (non-Javadoc)
160 * @see com.dtrules.admin.IRulesAdminService#getDecisionTable(java.lang.String, java.lang.String)
162 public RDecisionTable getDecisionTable(String rulesetname, String DecisionTableName) {
163 try {
164 RuleSet rs = rd.getRuleSet(RName.getRName(rulesetname));
165 return rs.getEntityFactory(session)
166 .findTable(RName.getRName(DecisionTableName));
167 } catch (RulesException e) {
168 return null;
172 /* (non-Javadoc)
173 * @see com.dtrules.admin.IRulesAdminService#getDecisionTables(java.lang.String)
175 public List getDecisionTables(String rulesetname) {
176 if(rd==null)return null;
177 try {
178 RuleSet rs = rd.getRuleSet(RName.getRName(rulesetname));
179 Iterator it = rs.getEntityFactory(session).getDecisionTableRNameIterator();
180 return getList(it);
181 } catch (RulesException e) {
182 return null;
186 @SuppressWarnings("unchecked")
187 private List getList(Iterator iterator){
188 List list = new ArrayList();
189 while(iterator.hasNext()){
190 list.add(((IRObject)iterator.next()).stringValue());
192 return list;
197 * Return the list of Entities known to the given ruleset
198 * @return List of Entity RName objects
199 * @see com.dtrules.admin.IRulesAdminService#getEntities(java.lang.String)
201 public List getEntities(String rulesetname) {
202 if(rd==null)return null;
203 try {
204 Iterator e = rd.getRuleSet(RName.getRName(rulesetname)).getEntityFactory(session)
205 .getEntityRNameIterator();
206 return getList(e);
207 } catch (RulesException e) {}
208 return null;
212 * Return the RuleSet associated with the given RuleSet Name
213 * @return RuleSet A set of Decision Tables and Entities which define a RuleSet
214 * @see com.dtrules.admin.IRulesAdminService#getRuleset(java.lang.String)
216 public RuleSet getRuleset(String RulesetName) {
217 if(rd==null)return null;
218 return rd.getRuleSet(RName.getRName(RulesetName));
222 * Returns the list of RuleSets known to this Rules Directory
223 * @return A List of RName objects giving the list Rule Sets
224 * @see com.dtrules.admin.IRulesAdminService#getRulesets()
226 public List<String> getRulesets() {
227 List<String> rulesets = new ArrayList<String>();
228 for(Iterator it = rd.getRulesets().keySet().iterator(); it.hasNext();){
229 RName name = (RName)it.next();
230 rulesets.add(name.stringValue());
232 return rulesets;
236 * Loads the XML defining the RulesDirectory. The given path must be a
237 * path and filename which is valid in the file system, or a valid Java
238 * resource, or a valid URL.
239 * @param pathtoDT
240 * @see com.dtrules.admin.IRulesAdminService#initialize(java.lang.String)
242 public void initialize(String pathtoDTrules) {
243 String path = "C:\\eclipse\\workspace\\EB_POC\\CA HCO Plan\\xml\\";
244 String file = path + "DTRules.xml";
245 if(pathtoDTrules != null){
246 file = pathtoDTrules;
249 try {
250 rd = new RulesDirectory("",file);
252 } catch (Exception e) {
253 e.printStackTrace();
259 * This method changes (potentially) the attributes of an attribute of an
260 * Entity. The REntityEntry attribute must be populated correctly.
262 * @param rulesetname The Ruleset which holds the Entity for which the
263 * attribute applies.
264 * @param attribute Contains the Entity Name and all the other meta data
265 * for the attribute to be changed.
267 * @see com.dtrules.admin.IRulesAdminService#updateAttribute(java.lang.String, com.dtrules.entity.REntityEntry)
269 public void updateAttribute(REntity entity, String rulesetname, REntityEntry attribute) throws RulesException {
270 entity.addAttribute(attribute);
274 * Updates the Decision Table XML specified in the RuleSet with the Decision Tables as
275 * currently held in memory.
277 public void saveDecisionTables(RSession session, String rulesetname) throws RulesException {
278 RuleSet rs = rd.getRuleSet(RName.getRName(rulesetname));
279 String filepath = rs.getFilepath();
280 String filename = rs.getDT_XMLName();
282 OutputStream out;
283 try {
284 out = new FileOutputStream(filepath+filename);
285 } catch (FileNotFoundException e) {
286 throw new RulesException(
287 "OutputFileCreationError",
288 "saveDecisionTables",
289 "An error occured openning the file: "+filepath+filename+"\n"+e
292 saveDecisionTables(out,session,rulesetname);
296 * Writes out the Decision Tables to the given output stream as the currently exist in
297 * Memory.
299 * @param out outputstream to write the decision tables to.
300 * @param session The session which gives us the outputstreams for debug statements and trace statements
301 * @param rulesetname The Rule Set to be written out to the output stream
302 * @throws RulesException
304 public void saveDecisionTables(OutputStream out, RSession session, String rulesetname) throws RulesException {
305 RuleSet rs = rd.getRuleSet(RName.getRName(rulesetname));
306 EntityFactory ef = rs.getEntityFactory(session);
308 PrintStream ps = new PrintStream(out);
309 Iterator<RName> tables = ef.getDecisionTableRNameIterator();
310 ps.println("<decision_tables>");
311 while(tables.hasNext()){
312 RName dtname = tables.next();
313 ef.getDecisionTable(dtname).writeXML(ps);
315 ps.println("\n</decision_tables>");
320 * Test function.
321 * @param args ignored.
323 public static void main(String args[]){
324 String path = "C:\\eclipse\\workspace\\EB_POC\\new_york_EB\\xml\\";
325 String file = path + "DTRules.xml";
327 RulesDirectory rd = new RulesDirectory("",file);
328 RuleSet rs = rd.getRuleSet(RName.getRName("ebdemo"));
329 RSession session;
330 try {
331 OutputStream out = new FileOutputStream("c:\\temp\\dt.xml");
332 session = new RSession(rs);
333 RulesAdminService admin = new RulesAdminService(session, rd);
335 admin.saveDecisionTables(out, session, "ebdemo");
336 } catch (Exception e1) {
337 System.out.println(e1.toString());
340 /* (non-Javadoc)
341 * @see com.dtrules.admin.IRulesAdminService#updateEntity(java.lang.String, com.dtrules.entity.REntity)
343 public void saveEDD(RSession session, String rulesetname) throws RulesException {
344 RuleSet rs = rd.getRuleSet(RName.getRName(rulesetname));
345 EntityFactory ef = rs.getEntityFactory(session);
346 String filepath = rs.getFilepath();
347 String filename = rs.getEDD_XMLName();
349 OutputStream out;
350 try {
351 out = new FileOutputStream(filepath+filename);
352 } catch (FileNotFoundException e) {
353 throw new RulesException(
354 "OutputFileCreationError",
355 "saveDecisionTables",
356 "An error occured openning the file: "+filepath+filename+"\n"+e
359 PrintStream ps = new PrintStream(out);
360 Iterator<RName> entities = ef.getEntityRNameIterator();
361 ps.println("<entity_data_dictionary>");
362 while(entities.hasNext()){
363 RName ename = entities.next();
364 ef.findRefEntity(ename).writeXML(ps);
366 ps.println("\n</entity_data_dictionary>");
369 /* (non-Javadoc)
370 * @see com.dtrules.admin.IRulesAdminService#updateRuleset(com.dtrules.session.RuleSet)
372 public void updateRuleset(RuleSet ruleset) {
373 // TODO Auto-generated method stub
379 * Given an incomplete table, this method returns a balanced table.
380 * Entries in the table provided can be 'y', 'n', '-', or ' '. If
381 * blank, then it is assumed that the caller assumes this should be
382 * flushed out. If the result will be larger than 16 columns, an
383 * null is returned. (You can't have a table larger than 16 columns).
384 * @param table -- A partial truth table.
385 * @return
387 public String[][] balanceTable(String [] [] table){
388 int rows = table.length;
389 if(rows>4||rows<=0)return null;
390 int cols = 1<<(rows);
392 String newTable[][] = new String [rows][cols];
394 for(int i=0; i< cols; i++){
395 for(int j=0;j<rows; j++){
396 newTable[j][i]= ((i>>(rows-1-j))&1)==1?"n":"y";
400 return newTable;
403 public final RulesDirectory getRd() {
404 return rd;
407 public final RSession getSession() {
408 return session;