1    package com.instantbank.component.job.ejb;
2    
3    import java.util.ArrayList;
4    import java.util.Collection;
5    import java.util.Iterator;
6    
7    // datasource and EJBException:
8    import javax.ejb.EJBException;
9    import javax.naming.InitialContext;
10   import javax.naming.NamingException;
11   
12   // for accessing DB:
13   import java.sql.Types;
14   import java.sql.Connection;
15   import java.sql.Statement;
16   import java.sql.PreparedStatement;
17   import java.sql.CallableStatement;
18   import java.sql.ResultSet;
19   import java.sql.SQLException;
20   import javax.sql.DataSource;
21   
22   // Job Model classes :
23   import com.instantbank.component.job.model.JobModel;
24   import com.instantbank.component.job.model.JobSELECTelement;
25   import com.instantbank.component.job.model.JobWHEREelement;
26   import com.instantbank.component.job.model.JobORDERelement;
27   
28   // common util:
29   import com.instantbank.common.utilcomponents.DatabaseNames;
30   import com.instantbank.common.utilcomponents.Debug;
31   import com.instantbank.common.utilcomponents.LetterTemplateExceptionMessage;
32   import com.instantbank.common.utilcomponents.LetterTemplateGlobals;
33   import com.instantbank.common.utilcomponents.JNDINames;
34   import com.instantbank.common.utilcomponents.DAOException;
35   import com.instantbank.common.utilcomponents.DAOUtil;
36   
37   /**
38    *  This class has JDBC calls required by EJB job for
39    *  implementing its services
40    *
41    * @author Instant-bank (Consuelo Franky)
42    * @created October 2002
43    */
44   public class JobDAO {
45   
46     // attributes corresponding to EJB state:
47     /**
48      * model of Job
49      */
50     private JobModel jobModel;
51   
52     // attributes for controlling EJB state update in the DB:
53     /**
54      * signales if job master data must be updated in the DB
55      */
56     private boolean jobMasterchanged;
57     /**
58      * signales if jobSELECT details must be updated in the DB
59      */
60     private boolean jobSELECTchanged;
61     /**
62      * signales if jobWHERE details must be updated in the DB
63      */
64     private boolean jobWHEREchanged;
65     /**
66      * signales if jobORDER details must be updated in the DB
67      */
68     private boolean jobORDERchanged;
69   
70     // attributes for connecting with the DB:
71     /**
72      * connection with the database
73      */
74     private Connection dbConnection = null;
75     /**
76      * datasource corresponding to the database
77      */
78     private DataSource datasource = null;
79   
80     // for debugging:
81     /**
82      * debug utility
83      */
84     private Debug debug = null;
85   
86   
87     // CONSTRUCTOR:
88     /**
89      *  Constructor: searchs the DataSource in the InitialContext
90      *
91      * @throws DAOException Description of the Exception
92      */
93     public JobDAO() throws DAOException {
94       debug = new Debug();
95       debug.setDebugginOn(false);
96       debug.setPreMessage("** JobDAO");
97   
98       // set the instance data:
99       this.datasource = DAOUtil.getDataSource(JNDINames.INSTANTBANKDB);
100    }
101  
102  
103    // METHODS GET ON ATTRIBUTES:
104  
105    /**
106     *  Getter method for jobModel attribute
107     *
108     * @return jobModel value
109     */
110    public JobModel getModel() {
111      return jobModel;
112    }
113  
114  
115    /**
116     *  Getter method for jobId
117     *
118     * @return jobId value (attribute of jobModel)
119     */
120    public Long getJobId() {
121      return jobModel.getJobId();
122    }
123  
124  
125    // METHODS SET ON ATTRIBUTES:
126  
127    /**
128     *  Setter method on jobId
129     *
130     * @param jobId The new jobId value (attribute of jobModel)
131     */
132    public void setJobId(Long jobId) {
133      jobModel.setJobId(jobId);
134    }
135  
136  
137    /**
138     *  Setter method on version
139     *
140     * @param version The new version value (attribute of jobModel)
141     */
142    public void setVersion(java.sql.Date version) {
143      jobModel.setVersion(version);
144    }
145  
146  
147    /**
148     *  Setter method on jobMasterchanged
149     *
150     * @param jobMasterchanged The new jobMasterchanged value
151     */
152    public void setJobMasterchanged(boolean jobMasterchanged) {
153      this.jobMasterchanged = jobMasterchanged;
154    }
155  
156  
157    /**
158     *  Setter method on jobSELECTchanged
159     *
160     * @param jobSELECTchanged The new jobSELECTchanged value
161     */
162    public void setJobSELECTchanged(boolean jobSELECTchanged) {
163      this.jobSELECTchanged = jobSELECTchanged;
164    }
165  
166  
167    /**
168     *  Setter method on jobWHEREchanged
169     *
170     * @param jobWHEREchanged The new jobWHEREchanged value
171     */
172    public void setJobWHEREchanged(boolean jobWHEREchanged) {
173      this.jobWHEREchanged = jobWHEREchanged;
174    }
175  
176  
177    /**
178     *  Setter method on jobORDERchanged
179     *
180     * @param jobORDERchanged The new jobORDERchanged value
181     */
182    public void setJobORDERchanged(boolean jobORDERchanged) {
183      this.jobORDERchanged = jobORDERchanged;
184    }
185  
186    // METHODS CORRESPONDING TO ejbMethods OF JobEJB:
187  
188    /**
189     *  Supports ejbCreate() method of Job EJB:
190     *  stores state of new ejb instance in the database
191     *  (inserting master and details of jobModel attribute);
192     *  updates jobId, with value assigned by DB;
193     *  updates jobModel with state master value of the database.
194     *
195     * @param jobModel state value of Job EJB
196     * @exception DAOException
197     */
198    public void ejbCreate(JobModel jobModel) throws DAOException {
199  
200      this.jobModel = jobModel;
201  
202      // master jobModel is inserted in DB:
203      insertJob();
204  
205      // get assigned jobId in the DB:
206      Long theJobId = selectJobId();
207      setJobId(theJobId);
208  
209      // details jobModel are inserted in DB:
210      if(jobModel.getJobSELECT() != null) {
211        insertJobSELECT();
212      }
213      if(jobModel.getJobWHERE() != null) {
214        insertJobWHERE();
215      }
216      if(jobModel.getJobORDER() != null) {
217        insertJobORDER();
218      }
219  
220      // jobModel (master part) is refreshed with values assigned by DB
221      // (i.e. jobId, version, activationDate,...)
222      selectJob();
223    }
224  
225  
226    /**
227     *  Supports ejbFindByPrimaryKey() method of Job EJB:
228     *  checks existence of ejb instance in the database
229     *
230     * @param jobId key value of instance
231     * @return key value of instance if it exists in the database
232     * @exception DAOException
233     */
234    public Long ejbFindByPrimaryKey(Long jobId) throws DAOException {
235      debug.println("ejbFindByPrimaryKey");
236      this.jobModel = new JobModel();
237      setJobId(jobId);
238      if(existsKey(jobId)) {
239        return getJobId();
240      }
241      else {
242        debug.println("job " + jobId + " does not exist");
243        throw new DAOException
244          (LetterTemplateExceptionMessage.NOT_EXISTS_JOB);
245      }
246    }
247  
248  
249    /**
250     *  Supports ejbFindByName() method of Job EJB:
251     *  checks existence of ejb instance in the database
252     *
253     * @param companyId current company
254     * @param name job name
255     * @return key value of instance if it exists in the database
256     * @exception DAOException
257     */
258    public Long ejbFindByName(String companyId, String name) throws DAOException {
259      debug.println("ejbFindByName");
260      this.jobModel = new JobModel();
261      Long jobIdanswer = existsJobByName(companyId, name);
262  
263      if(jobIdanswer != null) {
264        setJobId(jobIdanswer);
265        return getJobId();
266      }
267      else {
268        debug.println("job of name " + name + " does not exist");
269        throw new DAOException
270          (LetterTemplateExceptionMessage.NOT_EXISTS_JOB);
271      }
272    }
273  
274  
275    /**
276     *  Supports ejbRemove() method of Job EJB:
277     *  removes from database master and details of ejb instance
278     *
279     * @param jobId key value of instance
280     * @return true if the job was deleted; false otherwise
281     * @exception DAOException
282     */
283    public boolean ejbRemove(Long jobId) throws DAOException {
284      setJobId(jobId);
285      //deleteJobLogs();
286  
287      if(existsJobLogs()) {
288        return false;
289      }
290      else {
291        deleteJobSELECT();
292        deleteJobWHERE();
293        deleteJobORDER();
294        deleteJob();
295        return true;
296      }
297    }
298  
299  
300    /**
301     *  Supports ejbLoad() method of Job EJB:
302     *  loads from database master and details of instance
303     *
304     * @param jobId key value of instance
305     * @exception DAOException
306     */
307    public void ejbLoad(Long jobId) throws DAOException {
308      jobModel.setJobId(jobId);
309      selectJob();
310      selectJobSELECT();
311      selectJobWHERE();
312      selectJobORDER();
313    }
314  
315  
316    /**
317     *  Supports ejbStore() method of Job EJB:
318     *  updates in database master and details of instance
319     *
320     * @param jobModel state value of Job EJB
321     * @exception DAOException
322     */
323    public void ejbStore(JobModel jobModel) throws DAOException {
324      debug.println("method ejbStore");
325      this.jobModel = jobModel;
326  
327      // store master Job:
328      if(jobMasterchanged) {
329        updateJob();
330        debug.println("updateJob done");
331        java.sql.Date theVersion = selectVersion();
332        debug.println("theVersion gotten");
333        setVersion(theVersion);
334      }
335  
336      // store details of Job, replacing old versions:
337      if(jobSELECTchanged) {
338        deleteJobSELECT();
339        insertJobSELECT();
340        debug.println("jobSELECT updated");
341      }
342      if(jobWHEREchanged) {
343        deleteJobWHERE();
344        insertJobWHERE();
345        debug.println("jobWHERE updated");
346      }
347      if(jobORDERchanged) {
348        deleteJobORDER();
349        insertJobORDER();
350        debug.println("jobORDER updated");
351      }
352    }
353  
354  
355    // AUXILIARY JDBC METHODS FOR ejbFind...() :
356  
357    /**
358     * Checks existence of a Job in the database, from DatabaseNames.LETT_JOB
359     *
360     * @param jobId identifier of the job
361     * @return true    if the job exists in the database
362     *          false   otherwise
363     * @exception DAOException
364     */
365    private boolean existsKey(Long jobId) throws DAOException {
366      debug.println("existsKey");
367  
368      PreparedStatement ps = null;
369      ResultSet rs = null;
370      String queryExistsKey =
371        " SELECT job_id "
372        + " FROM " + DatabaseNames.LETT_JOB
373        + " WHERE job_id = ?  ";
374  
375      boolean answer = false;
376  
377      try {
378        dbConnection = DAOUtil.getDBConnection(datasource);
379        ps = dbConnection.prepareStatement(queryExistsKey);
380        ps.setLong(1, jobId.longValue());
381        ps.executeQuery();
382        rs = ps.getResultSet();
383        if(rs.next()) {
384          answer = true;
385        }
386      }
387      catch(Exception ae) {
388        debug.println("Exception:  " + ae.toString());
389        throw new DAOException
390          (LetterTemplateExceptionMessage.PROBLEM_CHECK_JOB + ae.getMessage());
391      }
392      finally {
393        DAOUtil.closeResultSet(rs);
394        DAOUtil.closePreparedStatement(ps);
395        DAOUtil.closeConnection(dbConnection);
396      }
397      return answer;
398    }
399  
400  
401    /**
402     * Checks existence of a Job in the database, from DatabaseNames.LETT_JOB
403     *
404     * @param companyId current company
405     * @param name job name
406     * @return job ID    if the job exists in the database
407     *          null      otherwise
408     * @exception DAOException
409     */
410    private Long existsJobByName(String companyId, String name) throws DAOException {
411      debug.println("existsJobByName");
412      PreparedStatement ps = null;
413      ResultSet rs = null;
414      String queryExistsKey =
415        " SELECT job_id "
416        + " FROM " + DatabaseNames.LETT_JOB
417        + " WHERE code_company = ?  AND name = ? ";
418  
419      long jobId;
420      Long answer = null;
421  
422      try {
423        dbConnection = DAOUtil.getDBConnection(datasource);
424        ps = dbConnection.prepareStatement(queryExistsKey);
425        ps.setLong(1, Long.parseLong(companyId));
426        ps.setString(2, name);
427        ps.executeQuery();
428        rs = ps.getResultSet();
429        if(rs.next()) {
430          jobId = rs.getLong(1);
431          answer = new Long(jobId);
432        }
433      }
434      catch(Exception ae) {
435        debug.println("Exception:  " + ae.toString());
436        throw new DAOException
437          (LetterTemplateExceptionMessage.PROBLEM_CHECK_JOB + ae.getMessage());
438      }
439      finally {
440        DAOUtil.closeResultSet(rs);
441        DAOUtil.closePreparedStatement(ps);
442        DAOUtil.closeConnection(dbConnection);
443      }
444      return answer;
445    }
446  
447  
448    // AUXILIARY JDBC METHODS FOR INSERTING DATA :
449  
450    /**
451     * Inserts the current Job (master part) in the database,
452     * in table: DatabaseNames.LETT_JOB
453     *
454     * @exception DAOException
455     */
456    private void insertJob() throws DAOException {
457      debug.println("insertJob");
458  
459      PreparedStatement ps = null;
460      String insertStrJob =
461        " INSERT INTO " + DatabaseNames.LETT_JOB
462        + "  (job_id, code_template, code_company, queue_type_id, "
463        + "   name,   description,   frequency,    status, "
464        + "   activation_date,       last_execution_date,  sql_text, "
465        + "   ftp_primary_id,        ftp_alternate_id, "
466        + "   last_changed_by,       last_changed_date) "
467        + " VALUES("
468        + DatabaseNames.SEQ_LETT_JOB + ".nextval," + " ?, ?, ?,"
469        + "   ?, ?, ?, ?, "
470        + "   SYSDATE,  ?, ?, "
471        + "   ?, ?, "
472        + "   ?, SYSDATE)";
473  
474      try {
475        dbConnection = DAOUtil.getDBConnection(datasource);
476        ps = dbConnection.prepareStatement(insertStrJob);
477        ps.setNull(1, Types.BIGINT);
478        ps.setLong(2, Long.parseLong(jobModel.getCompanyId()));
479        ps.setLong(3, jobModel.getQueueTypeId());
480        ps.setString(4, jobModel.getName());
481        ps.setString(5, jobModel.getDescription());
482        ps.setString(6, jobModel.getFrequency());
483        ps.setString(7, jobModel.getStatus());
484        ps.setNull(8, Types.DATE);
485        ps.setString(9, jobModel.getSqlText());
486        long ftpPrimaryId = jobModel.getFtpPrimaryId();
487        if(ftpPrimaryId == LetterTemplateGlobals.UNDEF) {
488          ps.setNull(10, Types.BIGINT);
489        }
490        else {
491          ps.setLong(10, ftpPrimaryId);
492        }
493        long ftpAlternateId = jobModel.getFtpAlternateId();
494        if(ftpAlternateId == LetterTemplateGlobals.UNDEF) {
495          ps.setNull(11, Types.BIGINT);
496        }
497        else {
498          ps.setLong(11, ftpAlternateId);
499        }
500        ps.setLong(12, jobModel.getUserId().longValue());
501        ps.executeUpdate();
502      }
503      catch(Exception ae) {
504        debug.println("Exception:  " + ae.toString());
505        throw new DAOException
506          (LetterTemplateExceptionMessage.PROBLEM_INSERT_JOB
507          + ae.getMessage());
508      }
509      finally {
510        DAOUtil.closePreparedStatement(ps);
511        DAOUtil.closeConnection(dbConnection);
512      }
513    }
514  
515  
516    /**
517     * Gets Id assigned by the database to the current job (jobId),
518     * in table DatabaseNames.LETT_JOB
519     *
520     * @return jobId
521     * @exception DAOException
522     */
523    private Long selectJobId() throws DAOException {
524      debug.println("selectJobId");
525  
526      PreparedStatement ps = null;
527      ResultSet rs = null;
528      String queryJobId =
529        " SELECT job_id "
530        + " FROM " + DatabaseNames.LETT_JOB
531        + " WHERE code_company = ?  AND name = ? ";
532  
533      Long answer = null;
534  
535      try {
536        dbConnection = DAOUtil.getDBConnection(datasource);
537        ps = dbConnection.prepareStatement(queryJobId);
538        ps.setLong(1, Long.parseLong(jobModel.getCompanyId()));
539        ps.setString(2, jobModel.getName());
540        ps.executeQuery();
541        rs = ps.getResultSet();
542        rs.next();
543        long theJobId = rs.getLong(1);
544        answer = new Long(theJobId);
545      }
546      catch(Exception ae) {
547        debug.println("Exception:  " + ae.toString());
548        throw new DAOException
549          (LetterTemplateExceptionMessage.PROBLEM_GET_JOBID
550          + ae.getMessage());
551      }
552      finally {
553        DAOUtil.closeResultSet(rs);
554        DAOUtil.closePreparedStatement(ps);
555        DAOUtil.closeConnection(dbConnection);
556      }
557      return answer;
558    }
559  
560  
561    /**
562     * Gets version (last_changed_date) of the current job,
563     * in table DatabaseNames.LETT_JOB
564     *
565     * @return version
566     * @exception DAOException
567     */
568    private java.sql.Date selectVersion() throws DAOException {
569      debug.println("selectVersion");
570  
571      PreparedStatement ps = null;
572      ResultSet rs = null;
573      String queryVersion =
574        " SELECT last_changed_date "
575        + " FROM " + DatabaseNames.LETT_JOB
576        + " WHERE job_id = ? ";
577  
578      java.sql.Date answer = null;
579  
580      try {
581        dbConnection = DAOUtil.getDBConnection(datasource);
582        ps = dbConnection.prepareStatement(queryVersion);
583        ps.setLong(1, getJobId().longValue());
584        ps.executeQuery();
585        rs = ps.getResultSet();
586        rs.next();
587        answer = rs.getDate(1);
588      }
589      catch(Exception ae) {
590        debug.println("Exception:  " + ae.toString());
591        throw new DAOException
592          (LetterTemplateExceptionMessage.PROBLEM_GET_JOBVERSION
593          + ae.getMessage());
594      }
595      finally {
596        DAOUtil.closeResultSet(rs);
597        DAOUtil.closePreparedStatement(ps);
598        DAOUtil.closeConnection(dbConnection);
599      }
600      return answer;
601    }
602  
603  
604    /**
605     * Inserts SELECT elements of the current Job in the database,
606     * in table: DatabaseNames.LETT_JOB_SELECT
607     *
608     * @exception DAOException
609     */
610    private void insertJobSELECT() throws DAOException {
611      debug.println("insertJobSELECT");
612      JobSELECTelement element;
613  
614      PreparedStatement ps = null;
615      String insertStrJobSELECT =
616        " INSERT INTO " + DatabaseNames.LETT_JOB_SELECT
617        + "  (job_id, sequence, field_id) "
618        + " VALUES( ?, ?, ?)";
619  
620      try {
621        dbConnection = DAOUtil.getDBConnection(datasource);
622        ps = dbConnection.prepareStatement(insertStrJobSELECT);
623  
624        for(Iterator it = jobModel.getJobSELECT().iterator();
625          it.hasNext(); ) {
626          element = (JobSELECTelement)it.next();
627          ps.setLong(1, getJobId().longValue());
628          ps.setInt(2, element.getSequence());
629          ps.setLong(3, element.getFieldId());
630          ps.executeUpdate();
631        }
632      }
633      catch(Exception ae) {
634        debug.println("Exception:  " + ae.toString());
635        throw new DAOException
636          (LetterTemplateExceptionMessage.PROBLEM_INSERT_JOBSELECT
637          + ae.getMessage());
638      }
639      finally {
640        DAOUtil.closePreparedStatement(ps);
641        DAOUtil.closeConnection(dbConnection);
642      }
643    }
644  
645  
646    /**
647     * Inserts WHERE elements of the current Job in the database,
648     * in table: DatabaseNames.LETT_JOB_WHERE
649     *
650     * @exception DAOException
651     */
652    private void insertJobWHERE() throws DAOException {
653      debug.println("insertJobWHERE");
654      JobWHEREelement element;
655  
656      PreparedStatement ps = null;
657      String insertStrJobWHERE =
658        " INSERT INTO " + DatabaseNames.LETT_JOB_WHERE
659        + "  (job_id, sequence, clause, field_id, rule_operator, "
660        + "   value, connector) "
661        + " VALUES( ?, ?, ?, ?, ?, ?, ?)";
662  
663      try {
664        dbConnection = DAOUtil.getDBConnection(datasource);
665        ps = dbConnection.prepareStatement(insertStrJobWHERE);
666  
667        for(Iterator it = jobModel.getJobWHERE().iterator();
668          it.hasNext(); ) {
669          element = (JobWHEREelement)it.next();
670          ps.setLong(1, getJobId().longValue());
671          ps.setInt(2, element.getSequence());
672          ps.setInt(3, element.getClause());
673          ps.setLong(4, element.getFieldId());
674          ps.setString(5, element.getRuleOperator());
675          ps.setString(6, element.getValue());
676          String connector = element.getConnector();
677          if(connector == null
678            || connector.equals(LetterTemplateGlobals.EMPTY_CONNECTOR)) {
679            ps.setNull(7, Types.VARCHAR);
680          }
681          else {
682            ps.setString(7, connector);
683          }
684          ps.executeUpdate();
685        }
686      }
687      catch(Exception ae) {
688        debug.println("Exception:  " + ae.toString());
689        throw new DAOException
690          (LetterTemplateExceptionMessage.PROBLEM_INSERT_JOBWHERE
691          + ae.getMessage());
692      }
693      finally {
694        DAOUtil.closePreparedStatement(ps);
695        DAOUtil.closeConnection(dbConnection);
696      }
697    }
698  
699  
700    /**
701     * Inserts ORDER elements of the current Job in the database,
702     * in table: DatabaseNames.LETT_JOB_ORDER
703     *
704     * @exception DAOException
705     */
706    private void insertJobORDER() throws DAOException {
707      debug.println("insertJobORDER");
708      JobORDERelement element;
709  
710      PreparedStatement ps = null;
711      String insertStrJobORDER =
712        " INSERT INTO " + DatabaseNames.LETT_JOB_ORDER
713        + "  (job_id, sequence, field_id, direction, unicity_member) "
714        + " VALUES( ?, ?, ?, ?, ?)";
715  
716      try {
717        dbConnection = DAOUtil.getDBConnection(datasource);
718        ps = dbConnection.prepareStatement(insertStrJobORDER);
719  
720        for(Iterator it = jobModel.getJobORDER().iterator();
721          it.hasNext(); ) {
722          element = (JobORDERelement)it.next();
723          ps.setLong(1, getJobId().longValue());
724          ps.setInt(2, element.getSequence());
725          ps.setLong(3, element.getFieldId());
726          ps.setString(4, element.getDirection());
727          ps.setString(5, element.getUnicityMember());
728          ps.executeUpdate();
729        }
730      }
731      catch(Exception ae) {
732        debug.println("Exception:  " + ae.toString());
733        throw new DAOException
734          (LetterTemplateExceptionMessage.PROBLEM_INSERT_JOBORDER
735          + ae.getMessage());
736      }
737      finally {
738        DAOUtil.closePreparedStatement(ps);
739        DAOUtil.closeConnection(dbConnection);
740      }
741    }
742  
743    // AUXILIARY JDBC METHODS FOR DELETING DATA (ejbRemove()):
744  
745    /**
746     * Deletes the current Job (master part) in the database,
747     * in table: DatabaseNames.LETT_JOB
748     *
749     * @exception DAOException
750     */
751    private void deleteJob() throws DAOException {
752      debug.println("deleteJob");
753  
754      PreparedStatement ps = null;
755      String deleteStrJob =
756        " DELETE FROM " + DatabaseNames.LETT_JOB
757        + " WHERE job_id = ? ";
758  
759      try {
760        dbConnection = DAOUtil.getDBConnection(datasource);
761        ps = dbConnection.prepareStatement(deleteStrJob);
762        ps.setLong(1, getJobId().longValue());
763        int num = ps.executeUpdate();
764        if(num == 0) {
765          throw new DAOException
766            (LetterTemplateExceptionMessage.PROBLEM_JOB_WAS_DELETED);
767        }
768      }
769      catch(Exception ae) {
770        debug.println("Exception:  " + ae.toString());
771        throw new DAOException
772          (LetterTemplateExceptionMessage.PROBLEM_DELETE_JOB
773          + ae.getMessage());
774      }
775      finally {
776        DAOUtil.closePreparedStatement(ps);
777        DAOUtil.closeConnection(dbConnection);
778      }
779    }
780  
781  
782    /**
783     * Deletes SELECT elements of the current Job in the database,
784     * in table: DatabaseNames.LETT_JOB_SELECT
785     *
786     * @exception DAOException
787     */
788    private void deleteJobSELECT() throws DAOException {
789      debug.println("deleteJobSELECT");
790      JobSELECTelement element;
791  
792      PreparedStatement ps = null;
793      String deleteStrJobSELECT =
794        " DELETE FROM " + DatabaseNames.LETT_JOB_SELECT
795        + " WHERE job_id = ? ";
796  
797      try {
798        dbConnection = DAOUtil.getDBConnection(datasource);
799        ps = dbConnection.prepareStatement(deleteStrJobSELECT);
800        ps.setLong(1, getJobId().longValue());
801        ps.executeUpdate();
802      }
803      catch(Exception ae) {
804        debug.println("Exception:  " + ae.toString());
805        throw new DAOException
806          (LetterTemplateExceptionMessage.PROBLEM_DELETE_JOBSELECT
807          + ae.getMessage());
808      }
809      finally {
810        DAOUtil.closePreparedStatement(ps);
811        DAOUtil.closeConnection(dbConnection);
812      }
813    }
814  
815  
816    /**
817     * Deletes WHERE elements of the current Job in the database,
818     * in table: DatabaseNames.LETT_JOB_WHERE
819     *
820     * @exception DAOException
821     */
822    private void deleteJobWHERE() throws DAOException {
823      debug.println("deleteJobWHERE");
824      JobSELECTelement element;
825  
826      PreparedStatement ps = null;
827      String deleteStrJobWHERE =
828        " DELETE FROM " + DatabaseNames.LETT_JOB_WHERE
829        + " WHERE job_id = ? ";
830  
831      try {
832        dbConnection = DAOUtil.getDBConnection(datasource);
833        ps = dbConnection.prepareStatement(deleteStrJobWHERE);
834        ps.setLong(1, getJobId().longValue());
835        ps.executeUpdate();
836      }
837      catch(Exception ae) {
838        debug.println("Exception:  " + ae.toString());
839        throw new DAOException
840          (LetterTemplateExceptionMessage.PROBLEM_DELETE_JOBWHERE
841          + ae.getMessage());
842      }
843      finally {
844        DAOUtil.closePreparedStatement(ps);
845        DAOUtil.closeConnection(dbConnection);
846      }
847    }
848  
849  
850    /**
851     * Deletes ORDER elements of the current Job in the database,
852     * in table: DatabaseNames.LETT_JOB_ORDER
853     *
854     * @exception DAOException
855     */
856    private void deleteJobORDER() throws DAOException {
857      debug.println("deleteJobORDER");
858      JobSELECTelement element;
859  
860      PreparedStatement ps = null;
861      String deleteStrJobSELECT =
862        " DELETE FROM " + DatabaseNames.LETT_JOB_ORDER
863        + " WHERE job_id = ? ";
864  
865      try {
866        dbConnection = DAOUtil.getDBConnection(datasource);
867        ps = dbConnection.prepareStatement(deleteStrJobSELECT);
868        ps.setLong(1, getJobId().longValue());
869        ps.executeUpdate();
870      }
871      catch(Exception ae) {
872        debug.println("Exception:  " + ae.toString());
873        throw new DAOException
874          (LetterTemplateExceptionMessage.PROBLEM_DELETE_JOBORDER
875          + ae.getMessage());
876      }
877      finally {
878        DAOUtil.closePreparedStatement(ps);
879        DAOUtil.closeConnection(dbConnection);
880      }
881    }
882  
883  
884    /**
885     * Checks if it exists log data of the current Job in the database,
886     * in table: DatabaseNames.LETT_JOB_LOG
887     *
888     * @return true   if log data exists
889     *          false  otherwise
890     * @exception DAOException
891     */
892    private boolean existsJobLogs() throws DAOException {
893      debug.println("existsJobLogs");
894  
895      PreparedStatement ps = null;
896      ResultSet rs = null;
897      boolean answer;
898  
899      String queryJobLog =
900        " SELECT job_log_id"
901        + " FROM " + DatabaseNames.LETT_JOB_LOG
902        + " WHERE job_id = ? ";
903  
904      try {
905        dbConnection = DAOUtil.getDBConnection(datasource);
906        ps = dbConnection.prepareStatement(queryJobLog);
907        ps.setLong(1, getJobId().longValue());
908        ps.executeQuery();
909        rs = ps.getResultSet();
910        if(rs.next()) {
911          answer = true;
912        }
913        else {
914          answer = false;
915        }
916        debug.println("answer=" + answer);
917      }
918      catch(Exception ae) {
919        debug.println("Exception:  " + ae.toString());
920        throw new DAOException
921          (LetterTemplateExceptionMessage.PROBLEM_CHECK_JOBLOGS
922          + ae.getMessage());
923      }
924      finally {
925        DAOUtil.closeResultSet(rs);
926        DAOUtil.closePreparedStatement(ps);
927        DAOUtil.closeConnection(dbConnection);
928      }
929      return answer;
930    }
931  
932  
933    /**
934     * Deletes log data of the current Job in the database,
935     * in tables: DatabaseNames.LETT_JOB_LOG, LETT_JOB_FTP_LOG
936     *
937     * @exception DAOException
938     */
939    private void deleteJobLogs() throws DAOException {
940      debug.println("deleteJobLogs");
941  
942      PreparedStatement ps = null;
943      PreparedStatement ps2 = null;
944      ResultSet rs = null;
945  
946      String queryJobLog =
947        " SELECT job_log_id"
948        + " FROM " + DatabaseNames.LETT_JOB_LOG
949        + " WHERE job_id = ? ";
950  
951      String deleteJobFTPLog =
952        " DELETE FROM " + DatabaseNames.LETT_JOB_FTP_LOG
953        + " WHERE job_log_id = ? ";
954  
955      String deleteJobLog =
956        " DELETE FROM " + DatabaseNames.LETT_JOB_LOG
957        + " WHERE job_id = ? ";
958  
959      try {
960        dbConnection = DAOUtil.getDBConnection(datasource);
961        ps = dbConnection.prepareStatement(queryJobLog);
962        ps2 = dbConnection.prepareStatement(deleteJobFTPLog);
963        ps.setLong(1, getJobId().longValue());
964        ps.executeQuery();
965        rs = ps.getResultSet();
966        while(rs.next()) {
967          long jobLogId = rs.getLong(1);
968          ps2.setLong(1, jobLogId);
969          ps2.executeUpdate();
970        }
971        DAOUtil.closePreparedStatement(ps);
972  
973        ps = dbConnection.prepareStatement(deleteJobLog);
974        ps.setLong(1, getJobId().longValue());
975        ps.executeUpdate();
976      }
977      catch(Exception ae) {
978        debug.println("Exception:  " + ae.toString());
979        throw new DAOException
980          (LetterTemplateExceptionMessage.PROBLEM_DELETE_JOBLOGS
981          + ae.getMessage());
982      }
983      finally {
984        DAOUtil.closePreparedStatement(ps2);
985        DAOUtil.closePreparedStatement(ps);
986        DAOUtil.closeConnection(dbConnection);
987      }
988    }
989  
990    // AUXILIARY JDBC METHODS FOR SELECTING DATA :
991  
992    /**
993     * Selects the current Job (master part) from the database,
994     * table: DatabaseNames.LETT_JOB
995     *
996     * @exception DAOException
997     */
998    private void selectJob() throws DAOException {
999      debug.println("selectJob");
1000 
1001     PreparedStatement ps = null;
1002     ResultSet rs = null;
1003     String queryJob =
1004       " SELECT "
1005       + "   code_template, code_company, queue_type_id, "
1006       + "   name,   description,   frequency,    status, "
1007       + "   activation_date,       last_execution_date,  sql_text, "
1008       + "   ftp_primary_id,        ftp_alternate_id, "
1009       + "   last_changed_by,       last_changed_date"
1010       + " FROM " + DatabaseNames.LETT_JOB
1011       + " WHERE job_id = ? ";
1012 
1013     try {
1014       dbConnection = DAOUtil.getDBConnection(datasource);
1015       ps = dbConnection.prepareStatement(queryJob);
1016       ps.setLong(1, getJobId().longValue());
1017       ps.executeQuery();
1018       rs = ps.getResultSet();
1019 
1020       if(!rs.next()) {
1021         throw new DAOException
1022           (LetterTemplateExceptionMessage.PROBLEM_JOB_WAS_DELETED);
1023       }
1024 
1025       long templateCode = rs.getLong(1);  // it can be SQL null
1026       if(rs.wasNull()) {
1027         templateCode = LetterTemplateGlobals.UNDEF;
1028       }
1029       String companyId = String.valueOf(rs.getLong(2));
1030       long queueTypeId = rs.getLong(3);
1031       String name = rs.getString(4);
1032       String description = rs.getString(5);
1033       String frequency = rs.getString(6);
1034       String status = rs.getString(7);
1035       java.sql.Date activationDate = rs.getDate(8);
1036       java.sql.Date lastExecutionDate = rs.getDate(9);  // it can be SQL null
1037       String sqlText = rs.getString(10);
1038       long ftpPrimaryId = rs.getLong(11);  // it can be SQL null
1039       if(rs.wasNull()) {
1040         ftpPrimaryId = LetterTemplateGlobals.UNDEF;
1041       }
1042       long ftpAlternateId = rs.getLong(12);  // it can be SQL null
1043       if(rs.wasNull()) {
1044         ftpAlternateId = LetterTemplateGlobals.UNDEF;
1045       }
1046       Long userId = new Long(rs.getLong(13));
1047       java.sql.Date version = rs.getDate(14);
1048 
1049       jobModel.setMaster(getJobId(), companyId, name, frequency,
1050         status, activationDate, ftpPrimaryId, ftpAlternateId,
1051         userId, version, templateCode, queueTypeId, description,
1052         sqlText, lastExecutionDate);
1053 
1054     }
1055     catch(Exception ae) {
1056       debug.println("Exception:  " + ae.toString());
1057       throw new DAOException
1058         (LetterTemplateExceptionMessage.PROBLEM_SELECT_JOB
1059         + ae.getMessage());
1060     }
1061     finally {
1062       DAOUtil.closeResultSet(rs);
1063       DAOUtil.closePreparedStatement(ps);
1064       DAOUtil.closeConnection(dbConnection);
1065     }
1066   }
1067 
1068 
1069   /**
1070    * Selects SELECT elements of the current Job from the database,
1071    * in table: DatabaseNames.LETT_JOB_SELECT
1072    *
1073    * @exception DAOException
1074    */
1075   private void selectJobSELECT() throws DAOException {
1076     debug.println("selectJobSELECT");
1077 
1078     PreparedStatement ps = null;
1079     ResultSet rs = null;
1080     ArrayList elements = new ArrayList();
1081     JobSELECTelement element = null;
1082 
1083     String queryJobSELECT =
1084       " SELECT sequence, field_id "
1085       + " FROM " + DatabaseNames.LETT_JOB_SELECT
1086       + " WHERE job_id = ? "
1087       + " ORDER BY sequence ";
1088 
1089     try {
1090       dbConnection = DAOUtil.getDBConnection(datasource);
1091       ps = dbConnection.prepareStatement(queryJobSELECT);
1092       ps.setLong(1, getJobId().longValue());
1093       ps.executeQuery();
1094       rs = ps.getResultSet();
1095 
1096       while(rs.next()) {
1097         int sequence = rs.getInt(1);
1098         long fieldId = rs.getLong(2);
1099         element = new JobSELECTelement(sequence, fieldId);
1100         elements.add(element);
1101       }
1102       jobModel.setJobSELECT(elements);
1103     }
1104     catch(Exception ae) {
1105       debug.println("Exception:  " + ae.toString());
1106       throw new DAOException
1107         (LetterTemplateExceptionMessage.PROBLEM_SELECT_JOBSELECT
1108         + ae.getMessage());
1109     }
1110     finally {
1111       DAOUtil.closeResultSet(rs);
1112       DAOUtil.closePreparedStatement(ps);
1113       DAOUtil.closeConnection(dbConnection);
1114     }
1115   }
1116 
1117 
1118   /**
1119    * Selects WHERE elements of the current Job from the database,
1120    * in table: DatabaseNames.LETT_JOB_WHERE
1121    *
1122    * @exception DAOException
1123    */
1124   private void selectJobWHERE() throws DAOException {
1125     debug.println("selectJobWHERE");
1126 
1127     PreparedStatement ps = null;
1128     ResultSet rs = null;
1129     ArrayList elements = new ArrayList();
1130     JobWHEREelement element = null;
1131 
1132     String queryJobWHERE =
1133       " SELECT sequence, clause, field_id, rule_operator, "
1134       + "        value, connector "
1135       + " FROM " + DatabaseNames.LETT_JOB_WHERE
1136       + " WHERE job_id = ? "
1137       + " ORDER BY sequence ";
1138 
1139     try {
1140       dbConnection = DAOUtil.getDBConnection(datasource);
1141       ps = dbConnection.prepareStatement(queryJobWHERE);
1142       ps.setLong(1, getJobId().longValue());
1143       ps.executeQuery();
1144       rs = ps.getResultSet();
1145 
1146       while(rs.next()) {
1147         int sequence = rs.getInt(1);
1148         int clause = rs.getInt(2);
1149         long fieldId = rs.getLong(3);
1150         String ruleOperator = rs.getString(4);
1151         String value = rs.getString(5);
1152         String connector = rs.getString(6);  // it can be SQL null
1153         if(connector == null) {
1154           connector = LetterTemplateGlobals.EMPTY_CONNECTOR;
1155         }
1156 
1157         element = new JobWHEREelement(sequence, clause, fieldId,
1158           ruleOperator, value, connector);
1159         elements.add(element);
1160       }
1161       jobModel.setJobWHERE(elements);
1162     }
1163     catch(Exception ae) {
1164       debug.println("Exception:  " + ae.toString());
1165       throw new DAOException
1166         (LetterTemplateExceptionMessage.PROBLEM_SELECT_JOBWHERE
1167         + ae.getMessage());
1168     }
1169     finally {
1170       DAOUtil.closeResultSet(rs);
1171       DAOUtil.closePreparedStatement(ps);
1172       DAOUtil.closeConnection(dbConnection);
1173     }
1174   }
1175 
1176 
1177   /**
1178    * Selects ORDER elements of the current Job from the database,
1179    * in table: DatabaseNames.LETT_JOB_ORDER
1180    *
1181    * @exception DAOException
1182    */
1183   private void selectJobORDER() throws DAOException {
1184     debug.println("selectJobORDER");
1185 
1186     PreparedStatement ps = null;
1187     ResultSet rs = null;
1188     ArrayList elements = new ArrayList();
1189     JobORDERelement element = null;
1190 
1191     String queryJobORDER =
1192       " SELECT sequence, field_id, direction, unicity_member "
1193       + " FROM " + DatabaseNames.LETT_JOB_ORDER
1194       + " WHERE job_id = ? "
1195       + " ORDER BY sequence ";
1196 
1197     try {
1198       dbConnection = DAOUtil.getDBConnection(datasource);
1199       ps = dbConnection.prepareStatement(queryJobORDER);
1200       ps.setLong(1, getJobId().longValue());
1201       ps.executeQuery();
1202       rs = ps.getResultSet();
1203 
1204       while(rs.next()) {
1205         int sequence = rs.getInt(1);
1206         long fieldId = rs.getLong(2);
1207         String direction = rs.getString(3);
1208         String unicityMember = rs.getString(4);
1209 
1210         element = new JobORDERelement
1211           (sequence, fieldId, direction, unicityMember);
1212         elements.add(element);
1213       }
1214       jobModel.setJobORDER(elements);
1215     }
1216     catch(Exception ae) {
1217       debug.println("Exception:  " + ae.toString());
1218       throw new DAOException
1219         (LetterTemplateExceptionMessage.PROBLEM_SELECT_JOBORDER
1220         + ae.getMessage());
1221     }
1222     finally {
1223       DAOUtil.closeResultSet(rs);
1224       DAOUtil.closePreparedStatement(ps);
1225       DAOUtil.closeConnection(dbConnection);
1226     }
1227   }
1228 
1229 
1230   // AUXILIARY JDBC METHODS FOR UPDATING MASTER DATA :
1231 
1232   /**
1233    * Updates the current Job (master part) in the database,
1234    * in table: DatabaseNames.LETT_JOB
1235    *
1236    * @exception DAOException
1237    */
1238   private void updateJob() throws DAOException {
1239     debug.println("updateJob");
1240 
1241     PreparedStatement ps = null;
1242     String updateStrJob =
1243       " UPDATE " + DatabaseNames.LETT_JOB + " SET "
1244       + "   code_template       = ?,"
1245       + "   code_company        = ?,"
1246       + "   queue_type_id       = ?,"
1247       + "   name                = ?,"
1248       + "   description         = ?,"
1249       + "   frequency           = ?,"
1250       + "   status              = ?,"
1251       + "   activation_date     = ?,"
1252       + "   last_execution_date = ?,"
1253       + "   sql_text            = ?,"
1254       + "   ftp_primary_id      = ?,"
1255       + "   ftp_alternate_id    = ?,"
1256       + "   last_changed_by     = ?,"
1257       + "   last_changed_date   = SYSDATE"
1258       + " WHERE job_id = ? ";
1259 
1260     try {
1261       dbConnection = DAOUtil.getDBConnection(datasource);
1262       ps = dbConnection.prepareStatement(updateStrJob);
1263       long templateCode = jobModel.getTemplateCode();
1264       if(templateCode == LetterTemplateGlobals.UNDEF) {
1265         ps.setNull(1, Types.BIGINT);
1266       }
1267       else {
1268         ps.setLong(1, templateCode);
1269       }
1270       ps.setLong(2, Long.parseLong(jobModel.getCompanyId()));
1271       ps.setLong(3, jobModel.getQueueTypeId());
1272       ps.setString(4, jobModel.getName());
1273       ps.setString(5, jobModel.getDescription());
1274       ps.setString(6, jobModel.getFrequency());
1275       ps.setString(7, jobModel.getStatus());
1276       ps.setDate(8, jobModel.getActivationDate());
1277 
1278       java.sql.Date lastExecutionDate = jobModel.getLastExecutionDate();
1279       if(lastExecutionDate == null) {
1280         ps.setNull(9, Types.DATE);
1281       }
1282       else {
1283         ps.setDate(9, lastExecutionDate);
1284       }
1285       ps.setString(10, jobModel.getSqlText());
1286       long ftpPrimaryId = jobModel.getFtpPrimaryId();
1287       if(ftpPrimaryId == LetterTemplateGlobals.UNDEF) {
1288         ps.setNull(11, Types.BIGINT);
1289       }
1290       else {
1291         ps.setLong(11, ftpPrimaryId);
1292       }
1293       long ftpAlternateId = jobModel.getFtpAlternateId();
1294       if(ftpAlternateId == LetterTemplateGlobals.UNDEF) {
1295         ps.setNull(12, Types.BIGINT);
1296       }
1297       else {
1298         ps.setLong(12, ftpAlternateId);
1299       }
1300       ps.setLong(13, jobModel.getUserId().longValue());
1301       ps.setLong(14, getJobId().longValue());
1302 
1303       int num = ps.executeUpdate();
1304       if(num == 0) {
1305         throw new DAOException
1306           (LetterTemplateExceptionMessage.PROBLEM_JOB_WAS_DELETED);
1307       }
1308     }
1309     catch(Exception ae) {
1310       debug.println("Exception:  " + ae.toString());
1311       throw new DAOException
1312         (LetterTemplateExceptionMessage.PROBLEM_UPDATE_JOB
1313         + ae.getMessage());
1314     }
1315     finally {
1316       DAOUtil.closePreparedStatement(ps);
1317       DAOUtil.closeConnection(dbConnection);
1318     }
1319   }
1320 
1321 }
1322 
1323