1    package com.instantbank.collections.companyInfo.ejb;
2    
3    import java.io.ByteArrayInputStream;
4    import java.io.PrintWriter;
5    import java.io.StringWriter;
6    import java.sql.ResultSet;
7    import java.sql.SQLException;
8    import java.sql.Statement;
9    import java.util.Calendar;
10   import java.util.Vector;
11   import javax.ejb.CreateException;
12   import javax.ejb.EJBContext;
13   import javax.ejb.SessionBean;
14   import javax.ejb.SessionContext;
15   import oracle.xml.parser.v2.DOMParser;
16   import oracle.xml.parser.v2.XMLDocument;
17   import oracle.xml.parser.v2.XMLNode;
18   import oracle.xml.parser.v2.XSLException;
19   import org.w3c.dom.Node;
20   import org.w3c.dom.NodeList;
21   import com.instantbank.collections.ach.AchDAO;
22   import com.instantbank.collections.ach.DataObject;
23   import com.instantbank.collections.util.DataAccess;
24   import com.instantbank.collections.util.InstantbankException;
25   import com.instantbank.collections.util.StringFormat;
26   import com.instantbank.collections.util.UniqueIDGenerator;
27   import com.instantbank.collections.util.XMLDataAccess;
28   import com.instantbank.collections.util.XMLUtils;
29   
30   public class CompanyServicesBean
31       implements SessionBean {
32   
33     private EJBContext context;
34   
35   
36     public void createDataObject(DataObject dataObject)
37        throws InstantbankException {
38       try {
39         AchDAO.create(dataObject);
40       }
41       catch(Exception e) {
42         e.printStackTrace();
43         setRollbackOnly();
44         throw new InstantbankException(e, "221001", "Failed to add DataObject: "
45           + dataObject.toString());
46       }
47     }
48   
49   
50     public void updateDataObject(DataObject dataObject)
51        throws InstantbankException {
52       try {
53         AchDAO.update(dataObject);
54       }
55       catch(Exception e) {
56         e.printStackTrace();
57         setRollbackOnly();
58         throw new InstantbankException(e, "221001", "Failed to update DataObject: "
59           + dataObject.toString());
60       }
61     }
62   
63   
64     public void removeDataObject(DataObject dataObject)
65        throws InstantbankException {
66       try {
67         AchDAO.remove(dataObject);
68       }
69       catch(Exception e) {
70         e.printStackTrace();
71         setRollbackOnly();
72         throw new InstantbankException(e, "221001", "Failed to remove DataObject: "
73           + dataObject.toString());
74       }
75     }
76   
77   
78     public String addCompany(String xml, long userId) throws InstantbankException {
79       DataAccess da = null;
80       DOMParser docParser;
81       String city = " ";
82       int cmp_dbpr;
83       int cmp_isaa;
84       int cmp_mibr;
85       int cmp_mpl;
86       String cmp_Name;
87       String cmp_Number;
88       int cmp_nup;
89       int cmp_ped;
90       int cmp_pewd;
91       long companyPk;
92       String country = " ";
93       String Id;
94       String line1 = " ";
95       String line2 = " ";
96       String phone = " ";
97       long pk;
98       long pk1;
99       String sql;
100      String state = " ";
101      long stateId = 0;
102      ByteArrayInputStream stream;
103      ResultSet SttId;
104      String TemporaryPathToDownload;
105      String typeId = " ";
106      XMLDocument xmlDoc;
107      String zipCode = " ";
108  
109      docParser = new DOMParser();
110      try {
111        da = new DataAccess();
112        da.connect();
113        companyPk = UniqueIDGenerator.instance().getNextId();
114        xmlDoc = null;
115        stream = new ByteArrayInputStream(xml.getBytes());
116        docParser.setValidationMode(false);
117        docParser.parse(stream);
118        xmlDoc = docParser.getDocument();
119        cmp_Number = xmlDoc.selectNodes("/Company/Number/text()").item(0).getNodeValue();
120        cmp_Name = xmlDoc.selectNodes("/Company/Name/text()").item(0).getNodeValue();
121        TemporaryPathToDownload = xmlDoc.selectNodes("/Company/TemporaryPath/text()").item(0).getNodeValue();
122        cmp_ped = Integer.parseInt(xmlDoc.selectNodes("/Company/Security/ped/text()").item(0).getNodeValue());
123        cmp_pewd = Integer.parseInt(xmlDoc.selectNodes("/Company/Security/pewd/text()").item(0).getNodeValue());
124        cmp_isaa = Integer.parseInt(xmlDoc.selectNodes("/Company/Security/isaa/text()").item(0).getNodeValue());
125        cmp_mibr = Integer.parseInt(xmlDoc.selectNodes("/Company/Security/mibr/text()").item(0).getNodeValue());
126        cmp_mpl = Integer.parseInt(xmlDoc.selectNodes("/Company/Security/mpl/text()").item(0).getNodeValue());
127        cmp_nup = Integer.parseInt(xmlDoc.selectNodes("/Company/Security/nup/text()").item(0).getNodeValue());
128        cmp_dbpr = Integer.parseInt(xmlDoc.selectNodes("/Company/Security/dbpr/text()").item(0).getNodeValue());
129        sql = "INSERT INTO COMPANIES (";
130        sql += "cmp_id, ";
131        sql += "cmp_number, ";
132        sql += "cmp_name, ";
133        sql += "cmp_last_changed_by, ";
134        sql += "cmp_last_changed_date, ";
135        sql += "cmp_pwd_expiration_days, ";
136        sql += "cmp_pwd_expiration_warn_days, ";
137        sql += "cmp_invalid_sign_on_attempts, ";
138        sql += "cmp_max_minutes_inactive, ";
139        sql += "cmp_min_password_length, ";
140        sql += "cmp_number_of_unique_passwords, ";
141        sql += "cmp_days_before_pwd_reuse";
142        sql += ") VALUES (";
143        sql += companyPk + ",";
144        sql += "'" + StringFormat.toSafeOracleString(cmp_Number) + "',";
145        sql += "'" + StringFormat.toSafeOracleString(cmp_Name) + "',";
146        sql += userId + ",";
147        sql += "SYSDATE" + ",";
148        sql += cmp_ped + ",";
149        sql += cmp_pewd + ",";
150        sql += cmp_isaa + ",";
151        sql += cmp_mibr + ",";
152        sql += cmp_mpl + ",";
153        sql += cmp_nup + ",";
154        sql += cmp_dbpr + ")";
155        da.makeInsert(sql);
156  
157        sql = "INSERT INTO COLLECTIONS_CONFIG (";
158        sql += "ccfg_cmp_id, ";
159        sql += "ccfg_download_path ";
160        sql += ") VALUES (";
161        sql += companyPk + ", '";
162        sql += StringFormat.toSafeOracleString(TemporaryPathToDownload) + "')";
163        da.makeInsert(sql);
164  
165        int addressNumber = xmlDoc.selectNodes("/Company/Addresses/Address").getLength();
166  
167        for(int i = 0; i < addressNumber; i++) {
168          XMLNode address = (XMLNode)xmlDoc.selectNodes("/Company/Addresses/Address").item(i);
169          saveCompanyAddress(da, companyPk, 0, address);
170        }
171        return (new Long(companyPk)).toString();
172      }
173      catch(Exception e) {
174        setRollbackOnly();
175        throw new InstantbankException(e, "121001", "Failed to add company to the database");
176      }
177      finally {
178        try {
179          if(da != null) {
180            da.disconnect();
181          }
182        }
183        catch(Exception e) {
184        }
185      }
186    }
187  
188  
189    public CompanyServicesBean() { }
190  
191  
192    private void deleteCompanyAddresses(DataAccess da, Vector ids) throws SQLException {
193      String addId;
194      int i;
195      String inClause;
196      String inClauseAdd;
197      ResultSet result = null;
198      String sql;
199      Statement st = null;
200  
201      try {
202        st = da.getConnection().createStatement();
203        inClause = "(";
204        for(i = 0; i < ids.size(); i++) {
205          inClause += ids.get(i);
206          if(i < ids.size() - 1) {
207            inClause += ",";
208          }
209        }
210        inClause += ")";
211  
212        if(!inClause.equals("()")) {
213          sql = "DELETE FROM ";
214          sql += "COMPANY_LOCATIONS ";
215          sql += "WHERE CMPL_CAD_ID IN " + inClause;
216          da.makeDelete(sql);
217  
218          sql = "SELECT CAD_ADD_ID FROM COMPANY_ADDRESSES WHERE CAD_ID IN " + inClause;
219          result = st.executeQuery(sql);
220          inClauseAdd = "(";
221          if(result.next()) {
222            while(true) {
223              inClauseAdd += result.getString(1);
224              if(!result.next()) {
225                break;
226              }
227              inClauseAdd += ",";
228            }
229          }
230          inClauseAdd = ")";
231  
232          sql = "DELETE FROM ";
233          sql += "COMPANY_ADDRESSES ";
234          sql += "WHERE ";
235          sql += "CAD_ID IN " + inClause;
236          da.makeDelete(sql);
237  
238          sql = "DELETE FROM ";
239          sql += "PHONE_NUMBERS ";
240          sql += "WHERE ";
241          sql += "PHN_ADD_ID IN " + inClauseAdd;
242          da.makeDelete(sql);
243  
244          sql = "DELETE FROM ";
245          sql += "ADDRESSES ";
246          sql += "WHERE ";
247          sql += "ADD_ID IN " + inClauseAdd;
248          da.makeDelete(sql);
249        }
250      }
251      catch(Exception e) {
252  
253      }
254      finally {
255        try {
256          if(result != null) {
257            result.close();
258          }
259          if(st != null) {
260            st.close();
261          }
262        }
263        catch(Exception e) {
264        }
265      }
266    }
267  
268  
269    public String getCalendar(Long companyId, int year) throws InstantbankException {
270      String ArrDays;
271      String Arr[];
272      XMLDataAccess da = null;
273      XMLDocument doc;
274      XMLNode root;
275      String sql;
276      long timeDay;
277      int topDays = 0;
278      String xml;
279      String xmlStr;
280  
281      try {
282        da = new XMLDataAccess("");
283        da.connect();
284        sql = "SELECT ";
285        sql += "clnd_year year,";
286        sql += "clnd_days days ";
287        sql += "FROM ";
288        sql += "calendars ";
289        sql += "WHERE ";
290        sql += "clnd_cmp_id = " + companyId.toString() + " AND ";
291        sql += "clnd_year = " + year;
292        doc = da.makeXMLSelect(sql, "Calendars", "Calendar");
293        StringWriter sw = new StringWriter();
294        PrintWriter pw = new PrintWriter(sw);
295        root = (XMLNode)doc.getDocumentElement();
296        root.print(pw);
297        sw = new StringWriter();
298        pw = new PrintWriter(sw);
299        doc.print(pw);
300        if(!doc.valueOf("Calendars/Calendar/year").equals(new String(""))) {
301          xml = XMLUtils.removeHeader(sw.toString());
302        }
303        else {
304          topDays = (((year % 4 == 0) & (year % 100 != 0)) || (year % 400 == 0)) ? topDays = 366 : 365;
305          Calendar calendar = Calendar.getInstance();
306          calendar.clear();
307          calendar.set(year, 0, 1);
308          ArrDays = "";
309          for(int i = 0; i < topDays; i++) {
310            if(calendar.get(calendar.DAY_OF_WEEK) == calendar.SUNDAY) {
311              ArrDays += "N";
312            }
313            else {
314              ArrDays += "P";
315            }
316            calendar.add(calendar.DATE, 1);
317          }
318          xmlStr = "<Calendars>";
319          xmlStr += "<Calendar>";
320          xmlStr += "<year>" + year + "</year>";
321          xmlStr += "<days>" + ArrDays + "</days>";
322          xmlStr += "</Calendar>";
323          xmlStr += "</Calendars>";
324          xml = xmlStr;
325        }
326  
327        return xml;
328      }
329      catch(Exception e) {
330        setRollbackOnly();
331        throw new InstantbankException(e, "121002", "Failed to read the calendar from the database");
332      }
333      finally {
334        try {
335          if(da != null) {
336            da.disconnect();
337          }
338        }
339        catch(Exception e) {
340        }
341      }
342    }
343  
344  
345    public String getCalendar(Long companyId, int fromYear, int toYear) throws InstantbankException {
346      String ArrDays;
347      String Arr[];
348      XMLDataAccess da = null;
349      XMLDocument doc;
350      XMLNode root;
351      String sql;
352      long timeDay;
353      int topDays = 0;
354      String xml;
355      String xmlStr;
356  
357      try {
358        da = new XMLDataAccess("");
359        da.connect();
360        sql = "SELECT ";
361        sql += "clnd_year year,";
362        sql += "clnd_days days ";
363        sql += "FROM ";
364        sql += "calendars ";
365        sql += "WHERE ";
366        sql += "clnd_cmp_id = " + companyId.toString() + " AND ";
367        sql += "(clnd_year between " + fromYear + " and " + toYear + ") ";
368        sql += "ORDER BY clnd_year";
369        xml = da.getXml(sql, "Calendars", "Calendar");
370        return xml;
371      }
372      catch(Exception e) {
373        setRollbackOnly();
374        throw new InstantbankException(e, "121002", "Failed to read the calendar from the database");
375      }
376      finally {
377        try {
378          if(da != null) {
379            da.disconnect();
380          }
381        }
382        catch(Exception e) {
383        }
384      }
385    }
386  
387  
388    public String getCompanies() throws InstantbankException {
389      XMLDataAccess da = null;
390      XMLDocument doc;
391      String xml;
392      String sql;
393  
394      try {
395        sql = "SELECT ";
396        sql += "CMP_ID Id,";
397        sql += "CMP_NAME Name ";
398        sql += "FROM ";
399        sql += "Companies ";
400        sql += "order by ";
401        sql += "upper(CMP_NAME) ";
402        da = new XMLDataAccess("");
403        da.connect();
404        doc = da.makeXMLSelect(sql, "CompaniesList", "Company");
405        StringWriter sw = new StringWriter();
406        PrintWriter pw = new PrintWriter(sw);
407        doc.print(pw);
408        return sw.toString();
409      }
410      catch(Exception e) {
411        setRollbackOnly();
412        throw new InstantbankException(e, "121003", "Failed to read companies from the database");
413      }
414      finally {
415        try {
416          if(da != null) {
417            da.disconnect();
418          }
419        }
420        catch(Exception e) {
421        }
422      }
423    }
424  
425  
426    public String getCompany(String companyId)
427       throws InstantbankException {
428      String addressesXML;
429      String sql;
430      StringBuffer xml;
431      XMLDataAccess Xda = null;
432  
433      try {
434        Xda = new XMLDataAccess("");
435        Xda.connect();
436        xml = getCompanySecurity(Xda.getDataAccess(), companyId);
437        addressesXML = getCompanyAddresses(Xda, companyId);
438        xml.append(addressesXML);
439        xml.append("</Company>");
440        return xml.toString();
441      }
442      catch(Exception e) {
443        setRollbackOnly();
444        throw new InstantbankException(e, "121004", "Failed to read company from the database");
445      }
446      finally {
447        try {
448          if(Xda != null) {
449            Xda.disconnect();
450          }
451        }
452        catch(Exception e) {
453        }
454      }
455    }
456  
457  
458    private String getCompanyAddresses(XMLDataAccess Xda, String companyId) throws InstantbankException {
459      XMLNode address;
460      NodeList addresses;
461      String addressId;
462      XMLDocument doc;
463      XMLNode root;
464      String sql;
465  
466      sql = "SELECT ";
467      sql += "cad_id id,";
468      sql += "add_adt_code type,";
469      sql += "(select phn_number from phone_numbers where phn_add_id=add_id and phn_pht_code='PR') phone,";
470      sql += "add_line1 line1,";
471      sql += "add_line2 line2,";
472      sql += "add_city city,";
473      sql += "stt_coun_id country,";
474      sql += "stt_code state,";
475      sql += "add_zip_code zipcode ";
476      sql += "FROM ";
477      sql += "addresses,";
478      sql += "company_addresses,";
479      sql += "states ";
480      sql += "WHERE ";
481      sql += "(cad_cmp_id = " + companyId + ") and (cad_add_id = add_id) and ";
482      sql += "(add_stt_id = stt_id)";
483      try {
484        doc = Xda.makeXMLSelect(sql, "Addresses", "Address");
485        root = (XMLNode)doc.getDocumentElement();
486        addresses = root.selectNodes("/Addresses/Address");
487        for(int i = 0; i < addresses.getLength(); i++) {
488          address = (XMLNode)addresses.item(i);
489          addressId = address.valueOf("./id");
490          StringBuffer sb = new StringBuffer();
491          sb.append("SELECT ");
492          sb.append("CMPL_ID id,");
493          sb.append("CMPL_PATH path,");
494          sb.append("CMPL_NAME name,");
495          sb.append("CMPL_IP_ADDRESS ipaddress,");
496          sb.append("CMPL_USER theuser,");
497          sb.append("CMPL_PASSWORD password ");
498          sb.append("FROM ");
499          sb.append("COMPANY_LOCATIONS ");
500          sb.append("WHERE ");
501          sb.append("(CMPL_CAD_ID = " + addressId + ")");
502          sql = sb.toString();
503          doc = Xda.makeXMLSelect(sql, "Locations", "Location", (Node)address);
504        }
505        root = (XMLNode)doc.getDocumentElement();
506        StringWriter sw = new StringWriter();
507        PrintWriter pw = new PrintWriter(sw);
508        root.print(pw);
509        return sw.toString();
510      }
511      catch(Exception e) {
512        setRollbackOnly();
513        throw new InstantbankException(e, "121005", "Failed to read the Company Addresses from the database");
514      }
515    }
516  
517  
518    public String getCompanyLocations(Long companyId)
519       throws InstantbankException {
520      XMLDataAccess da;
521      XMLDocument doc;
522      String sql;
523      String xml;
524  
525      da = new XMLDataAccess("");
526      try {
527        sql = "SELECT ";
528        sql += "cmpl_id id,";
529        sql += "cmpl_name name ";
530        sql += "FROM ";
531        sql += "company_locations,";
532        sql += "company_addresses ";
533        sql += "WHERE ";
534        sql += "cad_cmp_id = " + companyId + " AND ";
535        sql += "cmpl_cad_id = cad_id";
536        da.connect();
537        doc = da.makeXMLSelect(sql, "CompanyLocationsList", "CompanyLocations");
538        StringWriter sw = new StringWriter();
539        PrintWriter pw = new PrintWriter(sw);
540        doc.print(pw);
541        return sw.toString();
542      }
543      catch(Exception e) {
544        setRollbackOnly();
545        throw new InstantbankException(e, "121006", "Failed to read the Company Locations from the database");
546      }
547      finally {
548        try {
549          if(da != null) {
550            da.disconnect();
551          }
552        }
553        catch(Exception e) {
554        }
555      }
556    }
557  
558  
559    private StringBuffer getCompanySecurity(DataAccess da, String companyId) throws InstantbankException {
560      ResultSet resultSet = null;
561      String sql;
562      Statement st = null;
563      StringBuffer xml;
564  
565      sql = "SELECT ";
566      sql += "cmp_id id,";
567      sql += "cmp_number Cnumber,";
568      sql += "cmp_name name,";
569      sql += "ccfg_download_path TemporaryPath,";
570      sql += "users.user_userid lastChangedBy,";
571      sql += "to_char(cmp_last_changed_date,'mm-dd-yyyy') lastChangedDate,";
572      sql += "cmp_pwd_expiration_days ped,";
573      sql += "cmp_pwd_expiration_warn_days pewd,";
574      sql += "cmp_invalid_sign_on_attempts isaa,";
575      sql += "cmp_max_minutes_inactive mibr,";
576      sql += "cmp_min_password_length mpl,";
577      sql += "cmp_number_of_unique_passwords nup,";
578      sql += "cmp_days_before_pwd_reuse dbpr ";
579      sql += "FROM ";
580      sql += "companies,";
581      sql += "collections_config,";
582      sql += "users ";
583      sql += "WHERE ";
584      sql += "CMP_ID = '" + companyId + "' AND ";
585      sql += "cmp_id = ccfg_cmp_id AND ";
586      sql += "cmp_last_changed_by = user_id";
587      try {
588        st = da.getConnection().createStatement();
589        resultSet = st.executeQuery(sql);
590        resultSet.next();
591        xml = new StringBuffer();
592        xml.append(XMLUtils.xmlHeader());
593        xml.append("<Company>");
594        xml.append("<Id>" + resultSet.getString("id") + "</Id>");
595        xml.append("<Name>" + resultSet.getString("name") + "</Name>");
596        xml.append("<Number>" + resultSet.getString("Cnumber") + "</Number>");
597        xml.append("<TemporaryPath>" + resultSet.getString("TemporaryPath") + "</TemporaryPath>");
598        xml.append("<LastMaintainedBy>" + resultSet.getString("lastChangedBy") + "</LastMaintainedBy>");
599        xml.append("<DateMaintained>" + resultSet.getString("lastChangedDate") + "</DateMaintained>");
600        xml.append("<Security>");
601        xml.append(" <ped>" + resultSet.getString("ped") + "</ped>");
602        xml.append(" <pewd>" + resultSet.getString("pewd") + "</pewd>");
603        xml.append(" <isaa>" + resultSet.getString("isaa") + "</isaa>");
604        xml.append(" <mibr>" + resultSet.getString("mibr") + "</mibr>");
605        xml.append(" <mpl>" + resultSet.getString("mpl") + "</mpl>");
606        xml.append(" <nup>" + resultSet.getString("nup") + "</nup>");
607        xml.append(" <dbpr>" + resultSet.getString("dbpr") + "</dbpr>");
608        xml.append("</Security>");
609        return xml;
610      }
611      catch(Exception e) {
612        setRollbackOnly();
613        throw new InstantbankException(e, "121007", "Failed to read the company security from the database");
614      }
615      finally {
616        try {
617          if(resultSet != null) {
618            resultSet.close();
619          }
620          if(st != null) {
621            st.close();
622          }
623        }
624        catch(Exception e) {
625        }
626      }
627    }
628  
629  
630    public int getDBYear() throws InstantbankException {
631      DataAccess dataAccess = null;
632      Calendar date = Calendar.getInstance();
633      java.sql.Date dbDate = null;
634      ResultSet resultSet = null;
635      String sql;
636      Statement st = null;
637      int year;
638  
639      try {
640        date.clear();
641        dataAccess = new DataAccess();
642        dataAccess.connect();
643        st = dataAccess.getConnection().createStatement();
644        sql = "SELECT ";
645        sql += "SYSDATE ";
646        sql += "FROM ";
647        sql += "DUAL";
648        resultSet = st.executeQuery(sql);
649        while(resultSet.next()) {
650          dbDate = resultSet.getDate(1, date);
651        }
652        year = date.get(date.YEAR);
653        return year;
654      }
655      catch(Exception e) {
656        setRollbackOnly();
657        throw new InstantbankException(e, "121008", "Failed to read the year from the database");
658      }
659      finally {
660        try {
661          if(dataAccess != null) {
662            dataAccess.disconnect();
663          }
664        }
665        catch(Exception e) {
666        }
667      }
668    }
669  
670  
671    public String newCompany() throws InstantbankException {
672      StringBuffer xml = new StringBuffer();
673  
674      try {
675        xml.append(XMLUtils.xmlHeader());
676        xml.append("<Company>");
677        xml.append("<Id>0</Id>");
678        xml.append("<Name />");
679        xml.append("<Number />");
680        xml.append("<Country />");
681        xml.append("<LastMaintainedBy />");
682        xml.append("<DateMaintained />");
683        xml.append("<Security>");
684        xml.append(" <ped>0</ped>");
685        xml.append(" <pewd>0</pewd>");
686        xml.append(" <isaa>3</isaa>");
687        xml.append(" <mibr>0</mibr>");
688        xml.append(" <mpl>4</mpl>");
689        xml.append(" <nup>0</nup>");
690        xml.append(" <dbpr>0</dbpr>");
691        xml.append("</Security>");
692        xml.append("<Addresses />");
693        xml.append("</Company>");
694        return xml.toString();
695      }
696      catch(Exception e) {
697        throw new InstantbankException(e, "121009", "Failed in the load of the initial parameters for Company");
698      }
699    }
700  
701  
702    public void saveCalendar(Long companyId, int year, String dayArray) throws InstantbankException {
703      DataAccess da = null;
704      int rows;
705      String sqlUpdate;
706      String sqlInsert;
707  
708      try {
709        da = new DataAccess();
710        da.connect();
711        sqlUpdate = "UPDATE ";
712        sqlUpdate += "calendars ";
713        sqlUpdate += "SET ";
714        sqlUpdate += "clnd_days = '" + dayArray + "' ";
715        sqlUpdate += "WHERE ";
716        sqlUpdate += "clnd_cmp_id = " + companyId + " AND ";
717        sqlUpdate += "clnd_year = " + year;
718        rows = da.makeUpdate(sqlUpdate);
719        if(rows <= 0) {
720          sqlInsert = "INSERT INTO ";
721          sqlInsert += "calendars ";
722          sqlInsert += "(clnd_cmp_id,";
723          sqlInsert += "clnd_year,";
724          sqlInsert += "clnd_days) ";
725          sqlInsert += "VALUES (";
726          sqlInsert += companyId + ", ";
727          sqlInsert += year + ", '";
728          sqlInsert += dayArray + "')";
729          da.makeInsert(sqlInsert);
730        }
731      }
732      catch(Exception e) {
733        setRollbackOnly();
734        throw new InstantbankException(e, "121010", "Failed to save calendars to the database");
735      }
736      finally {
737        try {
738          if(da != null) {
739            da.disconnect();
740          }
741        }
742        catch(Exception e) {
743        }
744      }
745    }
746  
747  
748    public String saveCompany(String xml, long userId) throws InstantbankException {
749      Vector addressIds = new Vector();
750      DataAccess da = null;
751      DOMParser docParser;
752      String cmp_Number;
753      String cmp_Name;
754      int cmp_ped;
755      int cmp_pewd;
756      int cmp_isaa;
757      int cmp_mibr;
758      int cmp_mpl;
759      int cmp_nup;
760      int cmp_dbpr;
761      long companyPk;
762      long companyId;
763      int i;
764      String id;
765      int j;
766      long pk;
767      ResultSet result = null;
768      String sql;
769      Statement st = null;
770      ByteArrayInputStream stream;
771      String TemporaryPathToDownload;
772      XMLDocument xmlDoc = null;
773  
774      try {
775        da = new DataAccess();
776        da.connect();
777        st = da.getConnection().createStatement();
778        docParser = new DOMParser();
779        stream = new ByteArrayInputStream(xml.getBytes());
780        docParser.setValidationMode(false);
781        docParser.parse(stream);
782        xmlDoc = docParser.getDocument();
783        companyId = Long.parseLong(xmlDoc.selectNodes("/Company/Id/text()").item(0).getNodeValue());
784        cmp_Number = xmlDoc.selectNodes("/Company/Number/text()").item(0).getNodeValue();
785        cmp_Name = xmlDoc.selectNodes("/Company/Name/text()").item(0).getNodeValue();
786        cmp_ped = Integer.parseInt(xmlDoc.selectNodes("/Company/Security/ped/text()").item(0).getNodeValue());
787        cmp_pewd = Integer.parseInt(xmlDoc.selectNodes("/Company/Security/pewd/text()").item(0).getNodeValue());
788        cmp_isaa = Integer.parseInt(xmlDoc.selectNodes("/Company/Security/isaa/text()").item(0).getNodeValue());
789        cmp_mibr = Integer.parseInt(xmlDoc.selectNodes("/Company/Security/mibr/text()").item(0).getNodeValue());
790        cmp_mpl = Integer.parseInt(xmlDoc.selectNodes("/Company/Security/mpl/text()").item(0).getNodeValue());
791        cmp_nup = Integer.parseInt(xmlDoc.selectNodes("/Company/Security/nup/text()").item(0).getNodeValue());
792        cmp_dbpr = Integer.parseInt(xmlDoc.selectNodes("/Company/Security/dbpr/text()").item(0).getNodeValue());
793        TemporaryPathToDownload = xmlDoc.selectNodes("/Company/TemporaryPath/text()").item(0).getNodeValue();
794        sql = "UPDATE ";
795        sql += "COMPANIES ";
796        sql += "SET ";
797        sql += "cmp_number = '" + StringFormat.toSafeOracleString(cmp_Number) + "' , ";
798        sql += "cmp_name = '" + StringFormat.toSafeOracleString(cmp_Name) + "' , ";
799        sql += "cmp_last_changed_by = " + userId + " , ";
800        sql += "cmp_last_changed_date = SYSDATE , ";
801        sql += "cmp_pwd_expiration_days = " + cmp_ped + " , ";
802        sql += "cmp_pwd_expiration_warn_days = " + cmp_pewd + " , ";
803        sql += "cmp_invalid_sign_on_attempts = " + cmp_isaa + " , ";
804        sql += "cmp_max_minutes_inactive = " + cmp_mibr + " , ";
805        sql += "cmp_min_password_length = " + cmp_mpl + " , ";
806        sql += "cmp_number_of_unique_passwords = " + cmp_nup + " , ";
807        sql += "cmp_days_before_pwd_reuse = " + cmp_dbpr + " ";
808        sql += "WHERE ";
809        sql += "cmp_id = " + companyId;
810        da.makeUpdate(sql);
811  
812        sql = " UPDATE ";
813        sql += "collections_config ";
814        sql += " SET ";
815        sql += "ccfg_download_path = '" + StringFormat.toSafeOracleString(TemporaryPathToDownload) + "'";
816        sql += " WHERE ";
817        sql += "ccfg_cmp_id = " + companyId;
818        da.makeUpdate(sql);
819  
820        // Save the previous Address Ids in a vector
821        sql = "SELECT CAD_ID FROM COMPANY_ADDRESSES WHERE CAD_CMP_ID = " + companyId;
822        result = st.executeQuery(sql);
823        while(result.next()) {
824          addressIds.addElement(result.getString("CAD_ID"));
825        }
826  
827        // Saves each of the address nodes
828        int addressNumber = xmlDoc.selectNodes("/Company/Addresses/Address").getLength();
829        for(i = 0; i < addressNumber; i++) {
830          XMLNode address = (XMLNode)xmlDoc.selectNodes("/Company/Addresses/Address").item(i);
831          id = address.valueOf("./id");
832          pk = (new Long(id)).longValue();
833          saveCompanyAddress(da, companyId, pk, address);
834          for(j = 0; j < addressIds.size(); ) {
835            if((new Long((String)addressIds.get(j))).longValue() == pk) {
836              addressIds.remove(j);
837            }
838            else {
839              j++;
840            }
841          }
842        }
843  
844        // All the addresses found in the vector are deleted from the database
845        deleteCompanyAddresses(da, addressIds);
846  
847        return (new Long(companyId)).toString();
848      }
849      catch(Exception e) {
850        setRollbackOnly();
851        throw new InstantbankException(e, "121011", "Failed to update company to the database");
852      }
853      finally {
854        try {
855          if(result != null) {
856            result.close();
857          }
858          if(st != null) {
859            st.close();
860          }
861          if(da != null) {
862            da.disconnect();
863          }
864        }
865        catch(Exception e) {
866        }
867      }
868    }
869  
870  
871    private void saveCompanyAddress(DataAccess da, long companyId, long pk, XMLNode address) throws XSLException, SQLException, Exception {
872      int i;
873      String inClause;
874      Vector locationIds;
875      long pk1;
876      long pk2;
877      ResultSet result = null;
878      Statement st = null;
879      String sql;
880  
881      String line1 = address.valueOf("./line1");
882      String line2 = address.valueOf("./line2");
883      String country = address.valueOf("./country");
884      String city = address.valueOf("./city");
885      String state = address.valueOf("./state");
886      String zipCode = address.valueOf("./zipcode");
887      String phone = address.valueOf("./phone");
888      String typeId = address.valueOf("./type");
889      try {
890        if(pk == 0) {
891          // It is a new address in the database
892          pk1 = UniqueIDGenerator.instance().getNextId();
893          sql = "INSERT INTO ";
894          sql += "ADDRESSES (";
895          sql += "ADD_ID,";
896          sql += "ADD_LINE1,";
897          sql += "ADD_LINE2,";
898          sql += "ADD_CITY,";
899          sql += "ADD_STT_ID,";
900          sql += "ADD_ZIP_CODE,";
901          sql += "ADD_ADT_CODE) ";
902          sql += "VALUES (";
903          sql += pk1 + ",'";
904          sql += StringFormat.toSafeOracleString(line1) + "','";
905          sql += StringFormat.toSafeOracleString(line2) + "','";
906          sql += StringFormat.toSafeOracleString(city) + "',";
907          sql += "(select stt_id from states where stt_code='";
908          sql += state + "' and stt_coun_id='" + country + "')";
909          sql += ",'" + zipCode;
910          sql += "','" + typeId + "')";
911          da.makeInsert(sql);
912  
913          pk2 = UniqueIDGenerator.instance().getNextId();
914          sql = "INSERT INTO ";
915          sql += "PHONE_NUMBERS ";
916          sql += "(PHN_ID, ";
917          sql += "PHN_ADD_ID, ";
918          sql += "PHN_PHT_CODE, ";
919          sql += "PHN_NUMBER) ";
920          sql += "VALUES( ";
921          sql += pk2 + ",";
922          sql += pk1 + ",";
923          sql += "'PR','";
924          sql += StringFormat.toSafeOracleString(phone) + "')";
925          da.makeInsert(sql);
926  
927          pk = UniqueIDGenerator.instance().getNextId();
928          sql = "INSERT INTO COMPANY_ADDRESSES (";
929          sql += "CAD_ID,";
930          sql += "CAD_CMP_ID,";
931          sql += "CAD_ADD_ID";
932          sql += ") VALUES ( ";
933          sql += pk + ",";
934          sql += companyId + ",";
935          sql += pk1 + ")";
936          da.makeInsert(sql);
937        }
938        else {
939          sql = "SELECT CAD_ADD_ID FROM COMPANY_ADDRESSES WHERE CAD_ID=" + pk;
940          st = da.getConnection().createStatement();
941          result = st.executeQuery(sql);
942          result.next();
943          String addId = result.getString(1);
944  
945          sql = "UPDATE ADDRESSES SET ";
946          sql += "ADD_LINE1='" + StringFormat.toSafeOracleString(line1) + "',";
947          sql += "ADD_LINE2='" + StringFormat.toSafeOracleString(line2) + "',";
948          sql += "ADD_CITY='" + StringFormat.toSafeOracleString(city) + "',";
949          sql += "ADD_STT_ID=(select stt_id from states where stt_code='" + state + "' and stt_coun_id='" + country + "'),";
950          sql += "ADD_ZIP_CODE='" + zipCode + "',";
951          sql += "ADD_ADT_CODE='" + typeId + "' ";
952          sql += "WHERE ";
953          sql += "ADD_ID = " + addId;
954          da.makeUpdate(sql);
955  
956          sql = "UPDATE PHONE_NUMBERS SET ";
957          sql += "PHN_NUMBER='" + StringFormat.toSafeOracleString(phone) + "' ";
958          sql += "WHERE ";
959          sql += "PHN_ADD_ID=" + addId + " AND ";
960          sql += "PHN_PHT_CODE='PR' ";
961          da.makeUpdate(sql);
962        }
963  
964        // Save the previous Location Ids into a vector
965        locationIds = new Vector();
966        sql = "SELECT CMPL_ID FROM COMPANY_LOCATIONS WHERE CMPL_CAD_ID=" + pk;
967        st = da.getConnection().createStatement();
968        result = st.executeQuery(sql);
969        while(result.next()) {
970          locationIds.addElement(result.getString(1));
971        }
972  
973        // Saves the location nodes
974        int locationsNumber = address.selectNodes("./Locations/Location").getLength();
975        for(int j = 0; j < locationsNumber; j++) {
976          XMLNode location = (XMLNode)address.selectNodes("./Locations/Location").item(j);
977          String id = location.valueOf("./id");
978          String path = StringFormat.toSafeJavaString(location.valueOf("./path"));
979          String name = StringFormat.toSafeJavaString(location.valueOf("./name"));
980          String ipaddress = StringFormat.toSafeJavaString(location.valueOf("./ipaddress"));
981          String user = StringFormat.toSafeJavaString(location.valueOf("./user"));
982          String password = StringFormat.toSafeJavaString(location.valueOf("./password"));
983          long pkLoc = (new Long(id)).longValue();
984  
985          if(pkLoc == 0) {
986            pkLoc = UniqueIDGenerator.instance().getNextId();
987            sql = "INSERT INTO COMPANY_LOCATIONS(";
988            sql += "CMPL_ID,";
989            sql += "CMPL_CAD_ID,";
990            sql += "CMPL_PATH,";
991            sql += "CMPL_NAME,";
992            sql += "CMPL_IP_ADDRESS,";
993            sql += "CMPL_USER,";
994            sql += "CMPL_PASSWORD";
995            sql += ") VALUES (";
996            sql += pkLoc + ",";
997            sql += pk + ",";
998            sql += "'" + path + "',";
999            sql += "'" + name + "',";
1000           sql += "'" + ipaddress + "',";
1001           sql += "'" + user + "',";
1002           sql += "'" + password + "'";
1003           sql += ")";
1004           da.makeInsert(sql);
1005         }
1006         else {
1007           sql = "UPDATE COMPANY_LOCATIONS SET ";
1008           sql += "CMPL_PATH='" + path + "',";
1009           sql += "CMPL_NAME='" + name + "',";
1010           sql += "CMPL_IP_ADDRESS='" + ipaddress + "',";
1011           sql += "CMPL_USER='" + user + "',";
1012           sql += "CMPL_PASSWORD='" + password + "' ";
1013           sql += "WHERE ";
1014           sql += "CMPL_ID=" + pkLoc;
1015           da.makeUpdate(sql);
1016 
1017           // Finds the location Id in the vector. If found is cleared
1018           for(i = 0; i < locationIds.size(); ) {
1019             if((new Long((String)locationIds.get(i))).longValue() == pkLoc) {
1020               locationIds.remove(i);
1021             }
1022             else {
1023               i++;
1024             }
1025           }
1026         }
1027       }
1028 
1029       // All the location found in the vector are deleted from the database
1030       inClause = "(";
1031       for(i = 0; i < locationIds.size(); i++) {
1032         inClause += locationIds.get(i);
1033         if(i < locationIds.size() - 1) {
1034           inClause += ",";
1035         }
1036       }
1037       inClause += ")";
1038 
1039       if(!inClause.equals("()")) {
1040         sql = "DELETE FROM COMPANY_LOCATIONS WHERE CMPL_ID IN " + inClause;
1041         da.makeDelete(sql);
1042       }
1043 
1044     }
1045     catch(Exception e) {
1046     }
1047     finally {
1048       try {
1049         if(result != null) {
1050           result.close();
1051         }
1052         if(st != null) {
1053           st.close();
1054         }
1055         if(da != null) {
1056           da.disconnect();
1057         }
1058       }
1059       catch(Exception e) {
1060       }
1061     }
1062 
1063   }
1064 
1065 
1066   public void setSessionContext(SessionContext ctx) {
1067     this.context = ctx;
1068   }
1069 
1070 
1071   public void ejbCreate() throws CreateException {
1072     // TODO:  Add custom implementation.
1073   }
1074 
1075 
1076   public void ejbActivate() { }
1077 
1078 
1079   public void ejbPassivate() { }
1080 
1081 
1082   public void ejbRemove() { }
1083 
1084 
1085   private void setRollbackOnly() {
1086     try {
1087       this.context.setRollbackOnly();
1088     }
1089     catch(Exception e) {
1090     }
1091   }
1092 }
1093 
1094