View Javadoc

1   /**
2      This file is part of GoldenGate Project (named also GoldenGate or GG).
3   
4      Copyright 2009, Frederic Bregier, and individual contributors by the @author
5      tags. See the COPYRIGHT.txt in the distribution for a full listing of
6      individual contributors.
7   
8      All GoldenGate Project is free software: you can redistribute it and/or 
9      modify it under the terms of the GNU General Public License as published 
10     by the Free Software Foundation, either version 3 of the License, or
11     (at your option) any later version.
12  
13     GoldenGate is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17  
18     You should have received a copy of the GNU General Public License
19     along with GoldenGate .  If not, see <http://www.gnu.org/licenses/>.
20   */
21  package openr66.database.data;
22  
23  import goldengate.common.database.DbPreparedStatement;
24  import goldengate.common.database.DbSession;
25  import goldengate.common.database.data.AbstractDbData;
26  import goldengate.common.database.data.DbValue;
27  import goldengate.common.database.exception.GoldenGateDatabaseException;
28  import goldengate.common.database.exception.GoldenGateDatabaseNoConnectionException;
29  import goldengate.common.database.exception.GoldenGateDatabaseNoDataException;
30  import goldengate.common.database.exception.GoldenGateDatabaseSqlException;
31  import goldengate.common.file.DirInterface;
32  import goldengate.common.logging.GgInternalLogger;
33  import goldengate.common.logging.GgInternalLoggerFactory;
34  import goldengate.common.utility.GgStringUtils;
35  import goldengate.common.xml.XmlUtil;
36  import goldengate.common.xml.XmlValue;
37  
38  import java.io.File;
39  import java.io.StringReader;
40  import java.sql.SQLException;
41  import java.sql.Types;
42  import java.util.ArrayList;
43  import java.util.concurrent.ConcurrentHashMap;
44  
45  import openr66.configuration.RuleFileBasedConfiguration;
46  import openr66.context.R66Session;
47  import openr66.database.data.DbTaskRunner.TASKSTEP;
48  import openr66.protocol.configuration.Configuration;
49  import openr66.protocol.exception.OpenR66ProtocolSystemException;
50  import openr66.protocol.localhandler.packet.RequestPacket;
51  import openr66.protocol.utils.FileUtils;
52  
53  import org.dom4j.Document;
54  import org.dom4j.DocumentException;
55  import org.dom4j.io.SAXReader;
56  
57  /**
58   * Rule Table object
59   * @author Frederic Bregier
60   *
61   */
62  public class DbRule extends AbstractDbData {
63      /**
64       * Internal Logger
65       */
66      private static final GgInternalLogger logger = GgInternalLoggerFactory
67              .getLogger(DbRule.class);
68  
69      public static enum Columns {
70          HOSTIDS,
71          MODETRANS,
72          RECVPATH,
73          SENDPATH,
74          ARCHIVEPATH,
75          WORKPATH,
76          RPRETASKS,
77          RPOSTTASKS,
78          RERRORTASKS,
79          SPRETASKS,
80          SPOSTTASKS,
81          SERRORTASKS,
82          UPDATEDINFO,
83          IDRULE
84      }
85  
86      public static final int[] dbTypes = {
87              Types.LONGVARCHAR, Types.INTEGER, Types.VARCHAR, Types.VARCHAR,
88              Types.VARCHAR, Types.VARCHAR,
89              Types.LONGVARCHAR, Types.LONGVARCHAR, Types.LONGVARCHAR,
90              Types.LONGVARCHAR, Types.LONGVARCHAR, Types.LONGVARCHAR,
91              Types.INTEGER, Types.VARCHAR };
92  
93      public static final String table = " RULES ";
94  
95      /**
96       * HashTable in case of lack of database
97       */
98      private static final ConcurrentHashMap<String, DbRule> dbR66RuleHashMap =
99          new ConcurrentHashMap<String, DbRule>();
100 
101     /**
102      * Internal context XML fields
103      */
104     private static final String XMLHOSTIDS = "<"+RuleFileBasedConfiguration.XHOSTIDS+">";
105 
106     /**
107      * Internal context XML fields
108      */
109     private static final String XMLENDHOSTIDS = "</"+RuleFileBasedConfiguration.XHOSTIDS+">";
110 
111     /**
112      * Internal context XML fields
113      */
114     private static final String XMLHOSTID = "<"+RuleFileBasedConfiguration.XHOSTID+">";
115 
116     /**
117      * Internal context XML fields
118      */
119     private static final String XMLENDHOSTID = "</"+RuleFileBasedConfiguration.XHOSTID+">";
120 
121     /**
122      * Internal context XML fields
123      */
124     private static final String XMLTASKS = "<"+RuleFileBasedConfiguration.XTASKS+">";
125 
126     /**
127      * Internal context XML fields
128      */
129     private static final String XMLENDTASKS = "</"+RuleFileBasedConfiguration.XTASKS+">";
130 
131     /**
132      * Internal context XML fields
133      */
134     private static final String XMLTASK = "<"+RuleFileBasedConfiguration.XTASK+">";
135 
136     /**
137      * Internal context XML fields
138      */
139     private static final String XMLENDTASK = "</"+RuleFileBasedConfiguration.XTASK+">";
140 
141     /**
142      * Internal context XML fields
143      */
144     public static final String TASK_TYPE = "type";
145 
146     /**
147      * Internal context XML fields
148      */
149     public static final String TASK_PATH = "path";
150 
151     /**
152      * Internal context XML fields
153      */
154     public static final String TASK_DELAY = "delay";
155 
156     /**
157      * Global Id
158      */
159     public String idRule = null;
160 
161     /**
162      * The Name addresses (serverIds)
163      */
164     public String ids = null;
165 
166     /**
167      * Supported Mode for this rule (SENDMODE => SENDMD5MODE, RECVMODE =>
168      * RECVMD5MODE)
169      */
170     public int mode;
171 
172     /**
173      * The associated Recv Path
174      */
175     public String recvPath = null;
176 
177     /**
178      * The associated Send Path
179      */
180     public String sendPath = null;
181 
182     /**
183      * The associated Archive Path
184      */
185     public String archivePath = null;
186 
187     /**
188      * The associated Work Path
189      */
190     public String workPath = null;
191 
192     /**
193      * The associated Pre Tasks for Receiver
194      */
195     public String rpreTasks = null;
196 
197     /**
198      * The associated Post Tasks for Receiver
199      */
200     public String rpostTasks = null;
201 
202     /**
203      * The associated Error Tasks for Receiver
204      */
205     public String rerrorTasks = null;
206 
207     /**
208      * The associated Pre Tasks for Sender
209      */
210     public String spreTasks = null;
211 
212     /**
213      * The associated Post Tasks for Sender
214      */
215     public String spostTasks = null;
216 
217     /**
218      * The associated Error Tasks for Sender
219      */
220     public String serrorTasks = null;
221 
222     /**
223      * The Ids as an array
224      */
225     public String[] idsArray = null;
226 
227     /**
228      * The associated Pre Tasks as an array for Receiver
229      */
230     public String[][] rpreTasksArray = null;
231 
232     /**
233      * The associated Post Tasks as an array for Receiver
234      */
235     public String[][] rpostTasksArray = null;
236 
237     /**
238      * The associated Error Tasks as an array for Receiver
239      */
240     public String[][] rerrorTasksArray = null;
241 
242     /**
243      * The associated Pre Tasks as an array for Sender
244      */
245     public String[][] spreTasksArray = null;
246 
247     /**
248      * The associated Post Tasks as an array for Sender
249      */
250     public String[][] spostTasksArray = null;
251 
252     /**
253      * The associated Error Tasks as an array for Sender
254      */
255     public String[][] serrorTasksArray = null;
256 
257     private int updatedInfo = UpdatedInfo.UNKNOWN.ordinal();
258 
259     // ALL TABLE SHOULD IMPLEMENT THIS
260     public static final int NBPRKEY = 1;
261 
262     protected static final String selectAllFields = Columns.HOSTIDS.name() + "," +
263             Columns.MODETRANS.name() + "," + Columns.RECVPATH.name() + "," +
264             Columns.SENDPATH.name() + "," + Columns.ARCHIVEPATH.name() + "," +
265             Columns.WORKPATH.name() + "," +
266             Columns.RPRETASKS.name() + "," +
267             Columns.RPOSTTASKS.name() + "," + Columns.RERRORTASKS.name() + "," +
268             Columns.SPRETASKS.name() + "," +
269             Columns.SPOSTTASKS.name() + "," + Columns.SERRORTASKS.name() + "," +
270             Columns.UPDATEDINFO.name() + "," + Columns.IDRULE.name();
271 
272     protected static final String updateAllFields = Columns.HOSTIDS.name() +
273             "=?," + Columns.MODETRANS.name() + "=?," + Columns.RECVPATH.name() +
274             "=?," + Columns.SENDPATH.name() + "=?," +
275             Columns.ARCHIVEPATH.name() + "=?," + Columns.WORKPATH.name() +
276             "=?," + Columns.RPRETASKS.name() + "=?," + Columns.RPOSTTASKS.name() +
277             "=?," + Columns.RERRORTASKS.name() + "=?," +
278             Columns.SPRETASKS.name() + "=?," + Columns.SPOSTTASKS.name() +
279             "=?," + Columns.SERRORTASKS.name() + "=?," +
280             Columns.UPDATEDINFO.name() + "=?";
281 
282     protected static final String insertAllValues = " (?,?,?,?,?,?,?,?,?,?,?,?,?,?) ";
283 
284     /* (non-Javadoc)
285      * @see goldengate.common.database.data.AbstractDbData#initObject()
286      */
287     @Override
288     protected void initObject() {
289         primaryKey = new DbValue[]{new DbValue(idRule, Columns.IDRULE
290                 .name())};
291         otherFields = new DbValue[]{
292                 // HOSTIDS, MODETRANS, RECVPATH, SENDPATH, ARCHIVEPATH, WORKPATH,
293                 // PRETASKS, POSTTASKS, ERRORTASKS
294                 new DbValue(ids, Columns.HOSTIDS.name(), true),
295                 new DbValue(mode, Columns.MODETRANS.name()),
296                 new DbValue(recvPath, Columns.RECVPATH.name()),
297                 new DbValue(sendPath, Columns.SENDPATH.name()),
298                 new DbValue(archivePath, Columns.ARCHIVEPATH.name()),
299                 new DbValue(workPath, Columns.WORKPATH.name()),
300                 new DbValue(rpreTasks, Columns.RPRETASKS.name(), true),
301                 new DbValue(rpostTasks, Columns.RPOSTTASKS.name(), true),
302                 new DbValue(rerrorTasks, Columns.RERRORTASKS.name(), true),
303                 new DbValue(spreTasks, Columns.SPRETASKS.name(), true),
304                 new DbValue(spostTasks, Columns.SPOSTTASKS.name(), true),
305                 new DbValue(serrorTasks, Columns.SERRORTASKS.name(), true),
306                 new DbValue(updatedInfo, Columns.UPDATEDINFO.name()) };
307         allFields = new DbValue[]{
308                 otherFields[0], otherFields[1], otherFields[2], otherFields[3],
309                 otherFields[4], otherFields[5], otherFields[6], otherFields[7],
310                 otherFields[8], otherFields[9], otherFields[10],
311                 otherFields[11], otherFields[12], primaryKey[0] };
312     }
313 
314     /* (non-Javadoc)
315      * @see goldengate.common.database.data.AbstractDbData#getSelectAllFields()
316      */
317     @Override
318     protected String getSelectAllFields() {
319         return selectAllFields;
320     }
321 
322     /* (non-Javadoc)
323      * @see goldengate.common.database.data.AbstractDbData#getTable()
324      */
325     @Override
326     protected String getTable() {
327         return table;
328     }
329 
330     /* (non-Javadoc)
331      * @see goldengate.common.database.data.AbstractDbData#getInsertAllValues()
332      */
333     @Override
334     protected String getInsertAllValues() {
335         return insertAllValues;
336     }
337 
338     /* (non-Javadoc)
339      * @see goldengate.common.database.data.AbstractDbData#getUpdateAllFields()
340      */
341     @Override
342     protected String getUpdateAllFields() {
343         return updateAllFields;
344     }
345 
346     @Override
347     protected void setToArray() {
348         allFields[Columns.HOSTIDS.ordinal()].setValue(ids);
349         allFields[Columns.MODETRANS.ordinal()].setValue(mode);
350         allFields[Columns.RECVPATH.ordinal()].setValue(recvPath);
351         allFields[Columns.SENDPATH.ordinal()].setValue(sendPath);
352         allFields[Columns.ARCHIVEPATH.ordinal()].setValue(archivePath);
353         allFields[Columns.WORKPATH.ordinal()].setValue(workPath);
354         allFields[Columns.RPRETASKS.ordinal()].setValue(rpreTasks);
355         allFields[Columns.RPOSTTASKS.ordinal()].setValue(rpostTasks);
356         allFields[Columns.RERRORTASKS.ordinal()].setValue(rerrorTasks);
357         allFields[Columns.SPRETASKS.ordinal()].setValue(spreTasks);
358         allFields[Columns.SPOSTTASKS.ordinal()].setValue(spostTasks);
359         allFields[Columns.SERRORTASKS.ordinal()].setValue(serrorTasks);
360         allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo);
361         allFields[Columns.IDRULE.ordinal()].setValue(idRule);
362     }
363 
364     @Override
365     protected void setFromArray() throws GoldenGateDatabaseSqlException {
366         ids = (String) allFields[Columns.HOSTIDS.ordinal()].getValue();
367         mode = (Integer) allFields[Columns.MODETRANS.ordinal()].getValue();
368         recvPath = (String) allFields[Columns.RECVPATH.ordinal()].getValue();
369         sendPath = (String) allFields[Columns.SENDPATH.ordinal()].getValue();
370         archivePath = (String) allFields[Columns.ARCHIVEPATH.ordinal()]
371                 .getValue();
372         workPath = (String) allFields[Columns.WORKPATH.ordinal()].getValue();
373         rpreTasks = (String) allFields[Columns.RPRETASKS.ordinal()].getValue();
374         rpostTasks = (String) allFields[Columns.RPOSTTASKS.ordinal()].getValue();
375         rerrorTasks = (String) allFields[Columns.RERRORTASKS.ordinal()]
376                 .getValue();
377         spreTasks = (String) allFields[Columns.SPRETASKS.ordinal()].getValue();
378         spostTasks = (String) allFields[Columns.SPOSTTASKS.ordinal()].getValue();
379         serrorTasks = (String) allFields[Columns.SERRORTASKS.ordinal()]
380                 .getValue();
381         updatedInfo = (Integer) allFields[Columns.UPDATEDINFO.ordinal()]
382                 .getValue();
383         idRule = (String) allFields[Columns.IDRULE.ordinal()].getValue();
384         getIdsRule(ids);
385         rpreTasksArray = getTasksRule(rpreTasks);
386         rpostTasksArray = getTasksRule(rpostTasks);
387         rerrorTasksArray = getTasksRule(rerrorTasks);
388         spreTasksArray = getTasksRule(spreTasks);
389         spostTasksArray = getTasksRule(spostTasks);
390         serrorTasksArray = getTasksRule(serrorTasks);
391     }
392 
393     protected void setFromArrayClone(DbRule source) throws GoldenGateDatabaseSqlException {
394         ids = (String) allFields[Columns.HOSTIDS.ordinal()].getValue();
395         mode = (Integer) allFields[Columns.MODETRANS.ordinal()].getValue();
396         recvPath = (String) allFields[Columns.RECVPATH.ordinal()].getValue();
397         sendPath = (String) allFields[Columns.SENDPATH.ordinal()].getValue();
398         archivePath = (String) allFields[Columns.ARCHIVEPATH.ordinal()]
399                 .getValue();
400         workPath = (String) allFields[Columns.WORKPATH.ordinal()].getValue();
401         rpreTasks = (String) allFields[Columns.RPRETASKS.ordinal()].getValue();
402         rpostTasks = (String) allFields[Columns.RPOSTTASKS.ordinal()].getValue();
403         rerrorTasks = (String) allFields[Columns.RERRORTASKS.ordinal()]
404                 .getValue();
405         spreTasks = (String) allFields[Columns.SPRETASKS.ordinal()].getValue();
406         spostTasks = (String) allFields[Columns.SPOSTTASKS.ordinal()].getValue();
407         serrorTasks = (String) allFields[Columns.SERRORTASKS.ordinal()]
408                 .getValue();
409         updatedInfo = (Integer) allFields[Columns.UPDATEDINFO.ordinal()]
410                 .getValue();
411         idRule = (String) allFields[Columns.IDRULE.ordinal()].getValue();
412         if (source.ids == null) {
413             //No ids so setting to the default!
414             ids = null;
415             idsArray = null;
416         } else {
417             ids = source.ids;
418             idsArray = source.idsArray;
419         }
420         rpreTasksArray = source.rpreTasksArray;
421         rpostTasksArray = source.rpostTasksArray;
422         rerrorTasksArray = source.rerrorTasksArray;
423         spreTasksArray = source.spreTasksArray;
424         spostTasksArray = source.spostTasksArray;
425         serrorTasksArray = source.serrorTasksArray;
426     }
427 
428     /* (non-Javadoc)
429      * @see goldengate.common.database.data.AbstractDbData#getWherePrimaryKey()
430      */
431     @Override
432     protected String getWherePrimaryKey() {
433         return primaryKey[0].column + " = ? ";
434     }
435 
436     /* (non-Javadoc)
437      * @see goldengate.common.database.data.AbstractDbData#setPrimaryKey()
438      */
439     @Override
440     protected void setPrimaryKey() {
441         primaryKey[0].setValue(idRule);
442     }
443 
444     /**
445      * @param dbSession
446      * @param idRule
447      * @param ids
448      * @param mode
449      * @param recvPath
450      * @param sendPath
451      * @param archivePath
452      * @param workPath
453      * @param rpreTasks
454      * @param rpostTasks
455      * @param rerrorTasks
456      * @param spreTasks
457      * @param spostTasks
458      * @param serrorTasks
459      */
460     public DbRule(DbSession dbSession, String idRule, String ids, int mode, String recvPath,
461             String sendPath, String archivePath, String workPath,
462             String rpreTasks, String rpostTasks, String rerrorTasks,
463             String spreTasks, String spostTasks, String serrorTasks) {
464         super(dbSession);
465         this.idRule = idRule;
466         this.ids = ids;
467         this.mode = mode;
468         this.recvPath = recvPath;
469         this.sendPath = sendPath;
470         this.archivePath = archivePath;
471         this.workPath = workPath;
472         this.rpreTasks = rpreTasks;
473         this.rpostTasks = rpostTasks;
474         this.rerrorTasks = rerrorTasks;
475         this.spreTasks = spreTasks;
476         this.spostTasks = spostTasks;
477         this.serrorTasks = serrorTasks;
478         getIdsRule(this.ids);
479         rpreTasksArray = getTasksRule(this.rpreTasks);
480         rpostTasksArray = getTasksRule(this.rpostTasks);
481         rerrorTasksArray = getTasksRule(this.rerrorTasks);
482         spreTasksArray = getTasksRule(this.spreTasks);
483         spostTasksArray = getTasksRule(this.spostTasks);
484         serrorTasksArray = getTasksRule(this.serrorTasks);
485         // and reverse
486         this.rpreTasks = setTasksRule(rpreTasksArray);
487         this.rpostTasks = setTasksRule(rpostTasksArray);
488         this.rerrorTasks = setTasksRule(rerrorTasksArray);
489         this.spreTasks = setTasksRule(spreTasksArray);
490         this.spostTasks = setTasksRule(spostTasksArray);
491         this.serrorTasks = setTasksRule(serrorTasksArray);
492         setToArray();
493         isSaved = false;
494     }
495 
496     /**
497      * @param dbSession
498      * @param idRule
499      * @throws GoldenGateDatabaseException
500      */
501     public DbRule(DbSession dbSession, String idRule) throws GoldenGateDatabaseException {
502         super(dbSession);
503         this.idRule = idRule;
504         // load from DB
505         select();
506         /*
507         getIdsRule(ids);
508         rpreTasksArray = getTasksRule(this.rpreTasks);
509         rpostTasksArray = getTasksRule(this.rpostTasks);
510         rerrorTasksArray = getTasksRule(this.rerrorTasks);
511         spreTasksArray = getTasksRule(this.spreTasks);
512         spostTasksArray = getTasksRule(this.spostTasks);
513         serrorTasksArray = getTasksRule(this.serrorTasks);
514         */
515     }
516 
517     /**
518      * Constructor used from XML file
519      *
520      * @param dbSession
521      * @param idrule
522      * @param idsArrayRef
523      * @param recvpath
524      * @param sendpath
525      * @param archivepath
526      * @param workpath
527      * @param rpretasksArray
528      * @param rposttasksArray
529      * @param rerrortasksArray
530      * @param spretasksArray
531      * @param sposttasksArray
532      * @param serrortasksArray
533      */
534     public DbRule(DbSession dbSession, String idrule, String[] idsArrayRef, int mode,
535             String recvpath, String sendpath, String archivepath,
536             String workpath,
537             String[][] rpretasksArray, String[][] rposttasksArray, String[][] rerrortasksArray,
538             String[][] spretasksArray, String[][] sposttasksArray, String[][] serrortasksArray) {
539         super(dbSession);
540         idRule = idrule;
541         idsArray = idsArrayRef;
542         this.mode = mode;
543         recvPath = recvpath;
544         sendPath = sendpath;
545         archivePath = archivepath;
546         workPath = workpath;
547         rpreTasksArray = rpretasksArray;
548         rpostTasksArray = rposttasksArray;
549         rerrorTasksArray = rerrortasksArray;
550         spreTasksArray = spretasksArray;
551         spostTasksArray = sposttasksArray;
552         serrorTasksArray = serrortasksArray;
553         ids = setIdsRule(idsArrayRef);
554         rpreTasks = setTasksRule(rpretasksArray);
555         rpostTasks = setTasksRule(rposttasksArray);
556         rerrorTasks = setTasksRule(rerrortasksArray);
557         spreTasks = setTasksRule(spretasksArray);
558         spostTasks = setTasksRule(sposttasksArray);
559         serrorTasks = setTasksRule(serrortasksArray);
560         setToArray();
561         isSaved = false;
562     }
563     /**
564      * Delete all entries (used when purge and reload)
565      * @param dbSession
566      * @return the previous existing array of DbRule
567      * @throws GoldenGateDatabaseException
568      */
569     public static DbRule[] deleteAll(DbSession dbSession) throws GoldenGateDatabaseException {
570         DbRule[] result = getAllRules(dbSession);
571         dbR66RuleHashMap.clear();
572         if (dbSession == null) {
573             return result;
574         }
575         DbPreparedStatement preparedStatement = new DbPreparedStatement(
576                 dbSession);
577         try {
578             preparedStatement.createPrepareStatement("DELETE FROM " + table);
579             preparedStatement.executeUpdate();
580             return result;
581         } finally {
582             preparedStatement.realClose();
583         }
584     }
585     /*
586      * (non-Javadoc)
587      *
588      * @see openr66.databaseold.data.AbstractDbData#delete()
589      */
590     @Override
591     public void delete() throws GoldenGateDatabaseException {
592         dbR66RuleHashMap.remove(this.idRule);
593         if (dbSession == null) {
594             isSaved = false;
595             return;
596         }
597         super.delete();
598     }
599 
600     /*
601      * (non-Javadoc)
602      *
603      * @see openr66.databaseold.data.AbstractDbData#insert()
604      */
605     @Override
606     public void insert() throws GoldenGateDatabaseException {
607         if (isSaved) {
608             return;
609         }
610         dbR66RuleHashMap.put(this.idRule, this);
611         if (dbSession == null) {
612             isSaved = true;
613             return;
614         }
615         super.insert();
616     }
617 
618     /* (non-Javadoc)
619      * @see openr66.databaseold.data.AbstractDbData#exist()
620      */
621     @Override
622     public boolean exist() throws GoldenGateDatabaseException {
623         boolean result = dbR66RuleHashMap.containsKey(idRule);
624         if (result) {
625             return result;
626         }
627         if (dbSession == null) {
628             if (! result) {
629                 isSaved = false;
630             }
631             return result;
632         }
633         return super.exist();
634     }
635 
636     /*
637      * (non-Javadoc)
638      *
639      * @see openr66.databaseold.data.AbstractDbData#select()
640      */
641     @Override
642     public void select() throws GoldenGateDatabaseException {
643         DbRule rule = dbR66RuleHashMap.get(this.idRule);
644         if (rule != null) {
645             // copy info
646             for (int i = 0; i < allFields.length; i++){
647                 allFields[i].value = rule.allFields[i].value;
648             }
649             setFromArrayClone(rule);
650             if (recvPath == null) {
651                 recvPath = Configuration.configuration.inPath;
652             }
653             if (sendPath == null) {
654                 sendPath = Configuration.configuration.outPath;
655             }
656             if (archivePath == null) {
657                 archivePath = Configuration.configuration.archivePath;
658             }
659             if (workPath == null) {
660                 workPath = Configuration.configuration.workingPath;
661             }
662             isSaved = true;
663             return;
664         }
665         if (dbSession == null) {
666             if (rule == null) {
667                 throw new GoldenGateDatabaseNoDataException("No row found");
668             }
669         }
670         super.select();
671         if (recvPath == null) {
672             recvPath = Configuration.configuration.inPath;
673         }
674         if (sendPath == null) {
675             sendPath = Configuration.configuration.outPath;
676         }
677         if (archivePath == null) {
678             archivePath = Configuration.configuration.archivePath;
679         }
680         if (workPath == null) {
681             workPath = Configuration.configuration.workingPath;
682         }
683         setFromArray();
684     }
685 
686     /*
687      * (non-Javadoc)
688      *
689      * @see openr66.databaseold.data.AbstractDbData#update()
690      */
691     @Override
692     public void update() throws GoldenGateDatabaseException {
693         if (isSaved) {
694             return;
695         }
696         dbR66RuleHashMap.put(this.idRule, this);
697         if (dbSession == null) {
698             isSaved = true;
699             return;
700         }
701         super.update();
702     }
703     /**
704      * Private constructor for Commander only
705      */
706     private DbRule(DbSession session) {
707         super(session);
708     }
709     /**
710      * Get All DbRule from database or from internal hashMap in case of no database support
711      * @param dbSession may be null
712      * @return the array of DbRule
713      * @throws GoldenGateDatabaseNoConnectionException
714      * @throws GoldenGateDatabaseSqlException
715      */
716     public static DbRule[] getAllRules(DbSession dbSession) throws GoldenGateDatabaseNoConnectionException, GoldenGateDatabaseSqlException {
717         DbRule [] result = new DbRule[0];
718         if (! dbR66RuleHashMap.isEmpty() || dbSession == null) {
719             return dbR66RuleHashMap.values().toArray(result);
720         }
721         String request = "SELECT " +selectAllFields;
722             request += " FROM "+table;
723         DbPreparedStatement preparedStatement = new DbPreparedStatement(dbSession, request);
724         ArrayList<DbRule> dbArrayList = new ArrayList<DbRule>();
725         preparedStatement.executeQuery();
726         while (preparedStatement.getNext()) {
727             DbRule hostAuth = getFromStatement(preparedStatement);
728             dbArrayList.add(hostAuth);
729         }
730         preparedStatement.realClose();
731         dbArrayList.toArray(result);
732         return result;
733     }
734     /**
735      * For instance from Commander when getting updated information
736      * @param preparedStatement
737      * @return the next updated DbRule
738      * @throws GoldenGateDatabaseNoConnectionException
739      * @throws GoldenGateDatabaseSqlException
740      */
741     public static DbRule getFromStatement(DbPreparedStatement preparedStatement) throws GoldenGateDatabaseNoConnectionException, GoldenGateDatabaseSqlException {
742         DbRule dbRule = new DbRule(preparedStatement.getDbSession());
743         dbRule.getValues(preparedStatement, dbRule.allFields);
744         dbRule.setFromArray();
745         dbRule.isSaved = true;
746         return dbRule;
747     }
748     /**
749     *
750     * @return the DbPreparedStatement for getting Updated Object
751     * @throws GoldenGateDatabaseNoConnectionException
752     * @throws GoldenGateDatabaseSqlException
753     */
754    public static DbPreparedStatement getUpdatedPrepareStament(DbSession session) throws GoldenGateDatabaseNoConnectionException, GoldenGateDatabaseSqlException {
755        String request = "SELECT " +selectAllFields;
756        request += " FROM "+table+
757            " WHERE "+Columns.UPDATEDINFO.name()+" = "+
758            AbstractDbData.UpdatedInfo.TOSUBMIT.ordinal();
759        DbPreparedStatement prep = new DbPreparedStatement(session, request);
760        return prep;
761    }
762     /*
763      * (non-Javadoc)
764      *
765      * @see openr66.databaseold.data.AbstractDbData#changeUpdatedInfo(UpdatedInfo)
766      */
767     @Override
768     public void changeUpdatedInfo(UpdatedInfo info) {
769         if (updatedInfo != info.ordinal()) {
770             updatedInfo = info.ordinal();
771             allFields[Columns.UPDATEDINFO.ordinal()].setValue(updatedInfo);
772             isSaved = false;
773         }
774     }
775 
776     /**
777      * Get Ids from String. If it is not ok, then it sets the default values and
778      * return False, else returns True.
779      *
780      * @param idsref
781      * @return True if ok, else False (default values).
782      */
783     private boolean getIdsRule(String idsref) {
784         if (idsref == null) {
785             //No ids so setting to the default!
786             ids = null;
787             idsArray = null;
788             return false;
789         }
790         ids = idsref;
791         StringReader reader = new StringReader(idsref);
792         Document document = null;
793         try {
794             document = new SAXReader().read(reader);
795         } catch (DocumentException e) {
796             logger.warn("Unable to read the ids for Rule: " + idsref, e);
797             //No ids so setting to the default!
798             ids = null;
799             idsArray = null;
800             reader.close();
801             return false;
802         }
803         XmlValue []values = XmlUtil.read(document, 
804                 RuleFileBasedConfiguration.hostsDecls);
805         idsArray = RuleFileBasedConfiguration.getHostIds(values[0]);
806         reader.close();
807         return true;
808     }
809 
810     /**
811      * Get Tasks from String. If it is not ok, then it sets the default values
812      * and return new array of Tasks or null if in error.
813      *
814      * @param tasks
815      * @return Array of tasks or empty array if in error.
816      */
817     private String[][] getTasksRule(String tasks) {
818         if (tasks == null) {
819             //No tasks so setting to the default!
820             return new String[0][0];
821         }
822         StringReader reader = new StringReader(tasks);
823         Document document = null;
824         try {
825             document = new SAXReader().read(reader);
826         } catch (DocumentException e) {
827             logger.warn("Unable to read the tasks for Rule: " + tasks, e);
828             //No tasks so setting to the default!
829             reader.close();
830             return new String[0][0];
831         }
832         XmlValue[] values = XmlUtil.read(document, RuleFileBasedConfiguration.tasksDecl);
833         String [][] result = RuleFileBasedConfiguration.getTasksRule(values[0]);
834         reader.close();
835         return result;
836     }
837     
838     /**
839      * Initialized a ids String from args
840      *
841      * @param idsArray
842      * @return the new ids string
843      */
844     private static String setIdsRule(String[] idsArray) {
845         String ids = null;
846         if (idsArray != null) {
847             ids = XMLHOSTIDS;
848             for (String element: idsArray) {
849                 ids += XMLHOSTID + element + XMLENDHOSTID+"\n";
850             }
851             ids += XMLENDHOSTIDS;
852         }
853         return ids;
854     }
855 
856     /**
857      * Initialized a tasks String from args
858      *
859      * @param tasksArray
860      * @return the new tasks string
861      */
862     private static String setTasksRule(String[][] tasksArray) {
863         StringBuilder builder = new StringBuilder();
864         if (tasksArray != null) {
865             builder.append(XMLTASKS);
866             for (int i = 0; i < tasksArray.length; i ++) {
867                 builder.append(XMLTASK);
868                 builder.append('<').append(TASK_TYPE).append('>');
869                 builder.append(tasksArray[i][0]);
870                 builder.append("</").append(TASK_TYPE).append(">\n");
871                 builder.append('<').append(TASK_PATH).append('>');
872                 builder.append(tasksArray[i][1]);
873                 builder.append("</").append(TASK_PATH).append(">\n");
874                 builder.append('<').append(TASK_DELAY).append('>');
875                 builder.append(tasksArray[i][2]);
876                 builder.append("</").append(TASK_DELAY).append('>');
877                 builder.append(XMLENDTASK).append('\n');
878             }
879             builder.append(XMLENDTASKS);
880         }
881         return builder.toString();
882     }
883 
884     /**
885      * Get the full path from RecvPath (used only in copy MODETRANS)
886      *
887      * @param filename
888      * @return the full String path
889      * @throws OpenR66ProtocolSystemException
890      */
891     public String setRecvPath(String filename)
892             throws OpenR66ProtocolSystemException {
893         if (recvPath != null) {
894             return recvPath + DirInterface.SEPARATOR + filename;
895         }
896         return FileUtils.consolidatePath(Configuration.configuration.inPath,
897                 filename);
898     }
899 
900     /**
901      * Get the full path from sendPath
902      *
903      * @param filename
904      * @return the full String path
905      * @throws OpenR66ProtocolSystemException
906      */
907     public String setSendPath(String filename)
908             throws OpenR66ProtocolSystemException {
909         if (sendPath != null) {
910             File file = new File(filename);
911             String basename = file.getName();
912             return sendPath + DirInterface.SEPARATOR + basename;
913         }
914         return FileUtils.consolidatePath(Configuration.configuration.outPath,
915                 filename);
916     }
917 
918     /**
919      * Get the full path from archivePath
920      *
921      * @param filename
922      * @return the full String path
923      * @throws OpenR66ProtocolSystemException
924      */
925     public String setArchivePath(String filename)
926             throws OpenR66ProtocolSystemException {
927         if (archivePath != null) {
928             return archivePath + DirInterface.SEPARATOR + filename;
929         }
930         return FileUtils.consolidatePath(
931                 Configuration.configuration.archivePath, filename);
932     }
933 
934     /**
935      * Get the full path from workPath
936      *
937      * @param filename
938      * @return the full String path
939      * @throws OpenR66ProtocolSystemException
940      */
941     public String setWorkingPath(String filename)
942             throws OpenR66ProtocolSystemException {
943         if (workPath != null) {
944             return workPath + DirInterface.SEPARATOR + filename +
945                     Configuration.EXT_R66;
946         }
947         return FileUtils.consolidatePath(
948                 Configuration.configuration.workingPath, filename);
949     }
950 
951     /**
952      * Check if the given hostTo is in the allowed list
953      *
954      * @param hostId
955      * @return True if allow, else False
956      */
957     public boolean checkHostAllow(String hostId) {
958         if (idsArray == null || idsArray.length == 0) {
959             return true; // always true in this case
960         }
961         for (String element: idsArray) {
962             if (element.equalsIgnoreCase(hostId)) {
963                 return true;
964             }
965         }
966         return false;
967     }
968 
969     /**
970      *
971      * @return True if this rule is adapted for SENDMODE
972      */
973     public boolean isSendMode() {
974         return (!RequestPacket.isRecvMode(mode));
975     }
976 
977     /**
978      *
979      * @return True if this rule is adapted for RECVMODE
980      */
981     public boolean isRecvMode() {
982         return RequestPacket.isRecvMode(mode);
983     }
984 
985     /**
986      * Object to String
987      *
988      * @return the string that displays this object
989      * @see java.lang.Object#toString()
990      */
991     @Override
992     public String toString() {
993         return "Rule Name:" + idRule + " IDS:" + ids + " MODETRANS: " +
994                 RequestPacket.TRANSFERMODE.values()[mode].toString() +
995                 " RECV:" + recvPath + " SEND:" + sendPath + " ARCHIVE:" +
996                 archivePath + " WORK:" + workPath +
997                 "\nRPRET:" + rpreTasks + "\nRPOST:" + rpostTasks + "\nRERROR:" + rerrorTasks+
998                 "\nSPRET:" + spreTasks + "\nSPOST:" + spostTasks + "\nSERROR:" + serrorTasks;
999     }
1000     /**
1001      * 
1002      * @param isSender
1003      * @param step
1004      * @return a string that prints (debug) the tasks to execute
1005      */
1006     public String printTasks(boolean isSender, TASKSTEP step) {
1007         if (isSender) {
1008             switch (step) {
1009                 case PRETASK:
1010                     return "S:"+spreTasks;
1011                 case POSTTASK:
1012                     return "S:"+spostTasks;
1013                 case ERRORTASK:
1014                     return "S:"+serrorTasks;
1015                 default:
1016                     return "S:no task";
1017             }
1018         } else {
1019             switch (step) {
1020                 case PRETASK:
1021                     return "R:"+rpreTasks;
1022                 case POSTTASK:
1023                     return "R:"+rpostTasks;
1024                 case ERRORTASK:
1025                     return "R:"+rerrorTasks;
1026                 default:
1027                     return "R:no task";
1028             }
1029         }
1030     }
1031     /**
1032      * Object to String
1033      *
1034      * @return the string that displays this object
1035      * @see java.lang.Object#toString()
1036      */
1037     public String toShortString() {
1038         return "Rule Name:" + idRule + " MODETRANS: " +
1039             RequestPacket.TRANSFERMODE.values()[mode].toString();
1040     }
1041     /**
1042      *
1043      * @param session
1044      * @param rule
1045      * @param mode
1046      * @return the DbPreparedStatement according to the filter
1047      * @throws GoldenGateDatabaseNoConnectionException
1048      * @throws GoldenGateDatabaseSqlException
1049      */
1050     public static DbPreparedStatement getFilterPrepareStament(DbSession session,
1051             String rule, int mode)
1052         throws GoldenGateDatabaseNoConnectionException, GoldenGateDatabaseSqlException {
1053         DbPreparedStatement preparedStatement = new DbPreparedStatement(session);
1054         String request = "SELECT " +selectAllFields+" FROM "+table;
1055         String condition = null;
1056         if (rule != null) {
1057             condition = " WHERE "+Columns.IDRULE.name()+" LIKE '%"+rule+"%' ";
1058         }
1059         if (mode >= 0) {
1060             if (condition != null) {
1061                 condition += " AND ";
1062             } else {
1063                 condition = " WHERE ";
1064             }
1065             condition += Columns.MODETRANS.name()+" = ?";
1066         } else {
1067             condition = "";
1068         }
1069         preparedStatement.createPrepareStatement(request+condition+
1070                 " ORDER BY "+Columns.IDRULE.name());
1071         if (mode >= 0) {
1072             try {
1073                 preparedStatement.getPreparedStatement().setInt(1, mode);
1074             } catch (SQLException e) {
1075                 preparedStatement.realClose();
1076                 throw new GoldenGateDatabaseSqlException(e);
1077             }
1078         }
1079         return preparedStatement;
1080     }
1081     /**
1082      * @param session
1083      * @param body
1084      * @return the runner in Html format specified by body by replacing all instance of fields
1085      */
1086     public String toSpecializedHtml(R66Session session, String body) {
1087         StringBuilder builder = new StringBuilder(body);
1088         GgStringUtils.replace(builder, "XXXRULEXXX", idRule);
1089         GgStringUtils.replace(builder, "XXXIDSXXX", ids == null ? "" : ids);
1090         if (mode == RequestPacket.TRANSFERMODE.RECVMODE.ordinal()) {
1091             GgStringUtils.replace(builder, "XXXRECVXXX", "checked");
1092         } else if (mode == RequestPacket.TRANSFERMODE.SENDMODE.ordinal()) {
1093             GgStringUtils.replace(builder, "XXXSENDXXX", "checked");
1094         } else if (mode == RequestPacket.TRANSFERMODE.RECVMD5MODE.ordinal()) {
1095             GgStringUtils.replace(builder, "XXXRECVMXXX", "checked");
1096         } else if (mode == RequestPacket.TRANSFERMODE.SENDMD5MODE.ordinal()) {
1097             GgStringUtils.replace(builder, "XXXSENDMXXX", "checked");
1098         } else if (mode == RequestPacket.TRANSFERMODE.RECVTHROUGHMODE.ordinal()) {
1099             GgStringUtils.replace(builder, "XXXRECVTXXX", "checked");
1100         } else if (mode == RequestPacket.TRANSFERMODE.SENDTHROUGHMODE.ordinal()) {
1101             GgStringUtils.replace(builder, "XXXSENDTXXX", "checked");
1102         } else if (mode == RequestPacket.TRANSFERMODE.RECVMD5THROUGHMODE.ordinal()) {
1103             GgStringUtils.replace(builder, "XXXRECVMTXXX", "checked");
1104         } else if (mode == RequestPacket.TRANSFERMODE.SENDMD5THROUGHMODE.ordinal()) {
1105             GgStringUtils.replace(builder, "XXXSENDMTXXX", "checked");
1106         }
1107         GgStringUtils.replace(builder, "XXXRPXXX", recvPath == null ? "" : recvPath);
1108         GgStringUtils.replace(builder, "XXXSPXXX", sendPath == null ? "" : sendPath);
1109         GgStringUtils.replace(builder, "XXXAPXXX", archivePath == null ? "" : archivePath);
1110         GgStringUtils.replace(builder, "XXXWPXXX", workPath == null ? "" : workPath);
1111         GgStringUtils.replace(builder, "XXXRPTXXX", rpreTasks == null ? "" : rpreTasks);
1112         GgStringUtils.replace(builder, "XXXRSTXXX", rpostTasks == null ? "" : rpostTasks);
1113         GgStringUtils.replace(builder, "XXXRETXXX", rerrorTasks == null ? "" : rerrorTasks);
1114         GgStringUtils.replace(builder, "XXXSPTXXX", spreTasks == null ? "" : spreTasks);
1115         GgStringUtils.replace(builder, "XXXSSTXXX", spostTasks == null ? "" : spostTasks);
1116         GgStringUtils.replace(builder, "XXXSETXXX", serrorTasks == null ? "" : serrorTasks);
1117         return builder.toString();
1118     }
1119 
1120 }