1    package com.instantbank.collections.security.ejb;
2    
3    import java.io.ByteArrayInputStream;
4    import java.io.PrintWriter;
5    import java.io.StringWriter;
6    import java.rmi.RemoteException;
7    import java.sql.Connection;
8    import java.sql.PreparedStatement;
9    import java.sql.ResultSet;
10   import java.sql.SQLException;
11   import java.sql.Statement;
12   import javax.ejb.CreateException;
13   import javax.ejb.EJBContext;
14   import javax.ejb.SessionBean;
15   import javax.ejb.SessionContext;
16   import javax.naming.NamingException;
17   import oracle.xml.parser.v2.DOMParser;
18   import oracle.xml.parser.v2.XMLDocument;
19   import oracle.xml.parser.v2.XMLElement;
20   import oracle.xml.parser.v2.XMLNode;
21   import oracle.xml.parser.v2.XSLException;
22   import org.w3c.dom.NodeList;
23   import com.instantbank.collections.util.DataAccess;
24   import com.instantbank.collections.util.InstantbankException;
25   import com.instantbank.collections.util.ServiceLocator;
26   import com.instantbank.collections.util.StringFormat;
27   import com.instantbank.collections.util.UniqueIDGenerator;
28   import com.instantbank.collections.util.XMLDataAccess;
29   import com.instantbank.collections.util.XMLUtils;
30   
31   public class SecurityServicesBean
32       implements SessionBean {
33     private String ByChild;
34     private String ByParent;
35     private EJBContext context;
36     private String DateChild;
37     private String DateParent;
38     private String Children;
39     private String ChildrenGroupUser;
40     private Long IdChild;
41     private Long IdParent;
42     private Long lastChangedBy;
43     private String NameParent;
44     private String NameChild;
45     private NodeList nlIdParent;
46     private NodeList nlNameParent;
47     private NodeList nlByParent;
48     private NodeList nlDateParent;
49     private int nlLength;
50     private NodeList nlProfileParent;
51     private NodeList nlUserGroupsId;
52     private int nlUserGroupsLen;
53     private String Parent;
54     private String ProfileChild;
55     private String ProfileParent;
56   
57   
58     private void createPreviousPwd(long UppId, long UsrId) throws InstantbankException {
59       Connection con = null;
60       PreparedStatement ps = null;
61       ResultSet result = null;
62       try {
63         con = ServiceLocator.instance().getConnection();
64         ps = con.prepareStatement(
65           "insert into previous_passwords(" +
66           "upp_id, " +
67           "upp_date, " +
68           "upp_password, " +
69           "upp_user_id " +
70           ") select " +
71           " ?,sysdate, user_password, user_id " +
72           " from users where user_id = ?"
73           );
74         ps.setLong(1, UppId);
75         ps.setLong(2, UsrId);
76   
77         int n = ps.executeUpdate();
78         if(n != 1) {
79           throw new InstantbankException("131001", "Failed to create previous password to the database");
80         }
81       }
82       catch(Exception e) {
83         setRollbackOnly();
84         throw new InstantbankException(e, "131002", "Failed to create previous password to the database");
85       }
86       finally {
87         try {
88           if(ps != null) {
89             ps.close();
90           }
91           if(con != null) {
92             con.close();
93           }
94         }
95         catch(SQLException se) {
96           se.printStackTrace();
97         }
98       }
99     }
100  
101  
102    private void createUser(
103                            XMLDocument User,
104                            long UsrId,
105                            long companyId,
106                            long prfId
107                            ) throws InstantbankException {
108      Connection con = null;
109      PreparedStatement ps = null;
110      ResultSet result = null;
111      try {
112        con = ServiceLocator.instance().getConnection();
113        ps = con.prepareStatement(
114          "insert into users(" +
115          "user_id, " +
116          "user_cmp_id, " +
117          "user_usg_id, " +
118          "user_sprf_id, " +
119          "user_alias, " +
120          "user_first_name, " +
121          "user_last_name, " +
122          "user_date_last_logon, " +
123          "user_last_changed_by, " +
124          "user_last_changed_date, " +
125          "user_phone, " +
126          "user_extension, " +
127          "user_email, " +
128          "user_date_pwd_created, " +
129          "user_password, " +
130          "user_current_sign_on_attempts, " +
131          "user_status_flag, " +
132          "user_time_offset, " +
133          "user_time_of_last_transaction, " +
134          "user_title, " +
135          "user_userid, " +
136          "user_company_level_id, " +
137          "user_portafolio_level_id, " +
138          "user_legal_level_id, " +
139          "user_inactive_code, " +
140          "user_force_pwd_change_ind " +
141          ") values (" +
142          " ?,?,?,?,?,?,?,?,?,sysdate,?,?,?,sysdate,?,0,?,?,?,?,?,?,?,?,?,'1' " +
143          ")"
144          );
145        ps.setLong(1, UsrId);
146        ps.setLong(2, companyId);
147        ps.setLong(3, Long.parseLong(User.valueOf("/UserList/User/groupid")));
148        ps.setLong(4, prfId);
149        ps.setString(5, User.valueOf("/UserList/User/alias"));
150        ps.setString(6, User.valueOf("/UserList/User/firstname"));
151        ps.setString(7, User.valueOf("/UserList/User/lastname"));
152        ps.setNull(8, java.sql.Types.DATE);
153        ps.setLong(9, lastChangedBy.longValue());
154        ps.setString(10, User.valueOf("/UserList/User/phone"));
155        if(User.valueOf("/UserList/User/extension").equals("_")) {
156          ps.setNull(11, java.sql.Types.VARCHAR);
157        }
158        else {
159          ps.setString(11, User.valueOf("/UserList/User/extension"));
160        }
161        ps.setString(12, User.valueOf("/UserList/User/email"));
162        ps.setString(13, User.valueOf("/UserList/User/userid"));
163        ps.setLong(14, Long.parseLong(User.valueOf("/UserList/User/statusflag")));
164        ps.setLong(15, Long.parseLong(User.valueOf("/UserList/User/timeoffset")));
165        ps.setNull(16, java.sql.Types.DATE);
166        if(User.valueOf("/UserList/User/title").equals("_")) {
167          ps.setNull(17, java.sql.Types.VARCHAR);
168        }
169        else {
170          ps.setString(17, User.valueOf("/UserList/User/title"));
171        }
172        ps.setString(18, User.valueOf("/UserList/User/userid"));
173        ps.setNull(19, java.sql.Types.NUMERIC);
174        ps.setNull(20, java.sql.Types.NUMERIC);
175        ps.setNull(21, java.sql.Types.NUMERIC);
176        ps.setNull(22, java.sql.Types.NUMERIC);
177  
178        int n = ps.executeUpdate();
179        if(n != 1) {
180          throw new InstantbankException("131003", "Failed to create Users to the database");
181        }
182      }
183      catch(Exception e) {
184        setRollbackOnly();
185        throw new InstantbankException(e, "131004", "Failed to create Users to the database");
186      }
187      finally {
188        try {
189          if(ps != null) {
190            ps.close();
191          }
192          if(con != null) {
193            con.close();
194          }
195        }
196        catch(SQLException se) {
197          se.printStackTrace();
198        }
199      }
200    }
201  
202  
203    private void createUserGroup(
204                                 XMLDocument Groups,
205                                 long groupId,
206                                 long companyId,
207                                 long prfId
208                                 ) throws InstantbankException {
209      Connection con = null;
210      PreparedStatement ps = null;
211      ResultSet result = null;
212      try {
213        con = ServiceLocator.instance().getConnection();
214        ps = con.prepareStatement(
215          "insert into user_groups(" +
216          "usg_id, " +
217          "usg_cmp_id, " +
218          "usg_parent_id, " +
219          "usg_sprf_id, " +
220          "usg_name, " +
221          "usg_last_changed_by, " +
222          "usg_last_changed_date " +
223          ") values (" +
224          " ?,?,?,?,?,?,sysdate " +
225          ")"
226          );
227        ps.setLong(1, groupId);
228        ps.setLong(2, companyId);
229        if(Groups.valueOf("/GroupList/Group/parentid").equals("_")) {
230          ps.setNull(3, java.sql.Types.NUMERIC);
231        }
232        else {
233          ps.setLong(3, Long.parseLong(Groups.valueOf("/GroupList/Group/parentid")));
234        }
235        ps.setLong(4, prfId);
236        ps.setString(5, Groups.valueOf("/GroupList/Group/name"));
237        ps.setLong(6, lastChangedBy.longValue());
238  
239        int n = ps.executeUpdate();
240        if(n != 1) {
241          throw new InstantbankException("131005", "Failed to create User Groups to the database");
242        }
243      }
244      catch(Exception e) {
245        setRollbackOnly();
246        throw new InstantbankException(e, "131006", "Failed to create User Groups to the database");
247      }
248      finally {
249        try {
250          if(ps != null) {
251            ps.close();
252          }
253          if(con != null) {
254            con.close();
255          }
256        }
257        catch(SQLException se) {
258          se.printStackTrace();
259        }
260      }
261    }
262  
263  
264    public void ejbActivate() { }
265  
266  
267    public void ejbCreate() throws CreateException { }
268  
269  
270    public void ejbPassivate() { }
271  
272  
273    public void ejbRemove() { }
274  
275  
276    public String getChildGroups(Long groupId, int level)
277       throws InstantbankException {
278      XMLDataAccess da = null;
279      String result;
280      try {
281        da = new XMLDataAccess("");
282        da.connect();
283        result = getChildGroups(groupId, level, da);
284  
285        return result;
286      }
287      catch(Exception e) {
288        setRollbackOnly();
289        throw new InstantbankException(e, "131010", "Failed to retrieve children groups");
290      }
291      finally {
292        try {
293          if(da != null) {
294            da.disconnect();
295          }
296        }
297        catch(Exception e) {
298        }
299      }
300    }
301  
302  
303    public Long getCompanySessionTime(Long companyId) throws InstantbankException {
304      DataAccess dataAccess = null;
305      ResultSet resultSet = null;
306      Statement st = null;
307      String sql;
308      Long companyTimeOut = new Long("0");
309  
310      try {
311        dataAccess = new DataAccess();
312        dataAccess.connect();
313        st = dataAccess.getConnection().createStatement();
314        sql = "SELECT CMP_MAX_MINUTES_INACTIVE FROM COMPANIES WHERE CMP_ID = " + companyId;
315        resultSet = st.executeQuery(sql);
316        while(resultSet.next()) {
317          companyTimeOut = new Long(resultSet.getLong(1));
318        }
319        return companyTimeOut;
320      }
321      catch(Exception e) {
322        setRollbackOnly();
323        throw new InstantbankException(e, "121008", "Failed to get the company Time Out from the database");
324      }
325      finally {
326        try {
327          if(resultSet != null) {
328            resultSet.close();
329          }
330          if(st != null) {
331            st.close();
332          }
333          if(dataAccess != null) {
334            dataAccess.disconnect();
335          }
336        }
337        catch(Exception e) {
338        }
339      }
340    }
341  
342  
343  
344    private String getChildGroups(Long groupId, int level, XMLDataAccess da)
345       throws InstantbankException {
346      String child = new String();
347      String child1 = new String();
348      XMLDocument doc;
349      NodeList nlByChild;
350      int nlChdLen;
351      NodeList nlCodeChild;
352      NodeList nlIdChild;
353      NodeList nlNameChild;
354      NodeList nlProfileChild;
355      NodeList nlDateChild;
356      String result = new String();
357      String sql;
358      String xml;
359  
360      try {
361        Parent = new String();
362        sql = "SELECT usg_id id, usg_name name, usg_sprf_id profileid, NVL(user_userid, '_') changedby, NVL(to_char(usg_last_changed_date, 'MM-DD-YYYY'), '_') changeddate FROM user_groups, users WHERE usg_parent_id=" + groupId +
363          "AND usg_last_changed_by = user_id(+)";
364        doc = da.makeXMLSelect(sql, "ChildGroups", "Group");
365        nlIdChild = doc.selectNodes("/ChildGroups/Group/id/text()");
366        nlCodeChild = doc.selectNodes("/ChildGroups/Group/code/text()");
367        nlNameChild = doc.selectNodes("/ChildGroups/Group/name/text()");
368        nlProfileChild = doc.selectNodes("/ChildGroups/Group/profileid/text()");
369        nlByChild = doc.selectNodes("/ChildGroups/Group/changedby/text()");
370        nlDateChild = doc.selectNodes("/ChildGroups/Group/changeddate/text()");
371        nlChdLen = nlIdChild.getLength();
372        for(int i = 0; i < nlChdLen; i++) {
373          IdChild = new Long(nlIdChild.item(i).getNodeValue());
374          NameChild = nlNameChild.item(i).getNodeValue();
375          ProfileChild = nlProfileChild.item(i).getNodeValue();
376          ByChild = nlByChild.item(i).getNodeValue();
377          DateChild = nlDateChild.item(i).getNodeValue();
378          child1 = child;
379          child = makeXMLAttributes("id", IdChild.toString());
380          child = child + makeXMLAttributes("name", NameChild);
381          child = child + makeXMLAttributes("profileid", ProfileChild);
382          child = child + makeXMLAttributes("changedby", ByChild);
383          child = child + makeXMLAttributes("changeddate", DateChild);
384          if(level == 0) {
385            IdChild = new Long(nlIdChild.item(i).getNodeValue());
386            result = getChildGroups(IdChild, 0, da);
387          }
388          else if(level > 1) {
389            IdChild = new Long(nlIdChild.item(i).getNodeValue());
390            result = getChildGroups(IdChild, level - 1, da);
391          }
392          child = child + result;
393          child = child1 + makeXMLElement("Group", child);
394        }
395        child = makeXMLNode("ChildGroups", child, false);
396        result = child;
397        return result;
398      }
399      catch(Exception e) {
400        setRollbackOnly();
401        throw new InstantbankException(e, "131007", "Failed to retrieve children groups");
402      }
403    }
404  
405  
406    private String getChildGroupsUsers(Long groupId, int level, XMLDataAccess da)
407       throws InstantbankException {
408      XMLDocument doc;
409      String Child = new String();
410      String Child1 = new String();
411      String ChildUsers = new String();
412      Long grpId;
413      int nlChdLen;
414      NodeList nlIdChild;
415      NodeList nlCodeChild;
416      NodeList nlNameChild;
417      NodeList nlProfileChild;
418      NodeList nlByChild;
419      NodeList nlDateChild;
420      String Result = new String();
421      String sql;
422      String xml;
423  
424      try {
425        Parent = new String();
426        sql = "SELECT usg_id id, usg_name name FROM user_groups WHERE usg_parent_id=" + groupId;
427        doc = da.makeXMLSelect(sql, "ChildGroups", "Group");
428        nlIdChild = doc.selectNodes("/ChildGroups/Group/id/text()");
429        nlNameChild = doc.selectNodes("/ChildGroups/Group/name/text()");
430        nlChdLen = nlIdChild.getLength();
431        for(int i = 0; i < nlChdLen; i++) {
432          grpId = IdChild = new Long(nlIdChild.item(i).getNodeValue());
433          NameChild = nlNameChild.item(i).getNodeValue();
434          ChildUsers = getChildUsers(grpId, 1, da);
435          Child1 = Child;
436          Child = makeXMLAttributes("id", IdChild.toString());
437          Child = Child + makeXMLAttributes("name", NameChild);
438          Child = Child + ChildUsers;
439          if(level == 0) {
440            IdChild = new Long(nlIdChild.item(i).getNodeValue());
441            Result = getChildGroupsUsers(IdChild, 0, da);
442          }
443          else if(level > 1) {
444            IdChild = new Long(nlIdChild.item(i).getNodeValue());
445            Result = getChildGroupsUsers(IdChild, level - 1, da);
446          }
447          Child = Child + Result;
448          Child = Child1 + makeXMLElement("Group", Child);
449        }
450        Child = makeXMLNode("ChildGroups", Child, false);
451        Result = Child;
452        return Result;
453      }
454      catch(Exception e) {
455        setRollbackOnly();
456        throw new InstantbankException(e, "131008", "Failed to get children groups and users");
457      }
458    }
459  
460  
461    private String getChildGroupsUsers(Long groupId, int level, Long supervisorId, String objectType, DataAccess da) throws InstantbankException {
462      Long childGroupId;
463      String childGroupName;
464      ResultSet groupList = null;
465      boolean header;
466      Statement st = null;
467      String sql;
468      String xml;
469      String xmlGroups;
470      String xmlUsers;
471  
472      try {
473        st = da.getConnection().createStatement();
474        // Finds the first level groups
475        sql = "SELECT ";
476        sql += "usg_id id, usg_name name ";
477        sql += "FROM ";
478        sql += "user_groups ";
479        sql += "WHERE ";
480        sql += "usg_parent_id=" + groupId;
481        groupList = st.executeQuery(sql);
482  
483        header = false;
484        xml = "";
485        while(groupList.next()) {
486          childGroupId = new Long(groupList.getLong(1));
487          childGroupName = groupList.getString(2);
488          if(isGroupSupervisedBy(childGroupId, supervisorId, objectType, da)) {
489            xmlUsers = getChildUsers(childGroupId, new Long(0), objectType, da);
490            xmlGroups = getChildGroupsUsers(childGroupId, 0, new Long(0), objectType, da);
491          }
492          else {
493            xmlUsers = getChildUsers(childGroupId, supervisorId, objectType, da);
494            xmlGroups = getChildGroupsUsers(childGroupId, 0, supervisorId, objectType, da);
495          }
496          if(!xmlUsers.equals("") || !xmlGroups.equals("")) {
497            if(!header) {
498              xml = "<ChildGroups>";
499              header = true;
500            }
501            xml += "<Group>";
502            xml += "<id>" + childGroupId + "</id>";
503            xml += "<name>" + childGroupName + "</name>";
504            xml += xmlUsers;
505            xml += xmlGroups;
506            xml += "</Group>";
507          }
508        }
509        if(header) {
510          xml += "</ChildGroups>";
511        }
512        return xml;
513      }
514      catch(Exception e) {
515        setRollbackOnly();
516        throw new InstantbankException(e, "131012", "Failed to retrieve children groups and users for supervisor " + supervisorId);
517      }
518      finally {
519        try {
520          if(groupList != null) {
521            groupList.close();
522          }
523          if(st != null) {
524            st.close();
525          }
526        }
527        catch(Exception e) {
528        }
529      }
530    }
531  
532  
533    public String getChildUsers(Long groupId, int level)
534       throws InstantbankException {
535      XMLDataAccess da = null;
536      String result;
537      try {
538        da = new XMLDataAccess("");
539        da.connect();
540        result = getChildUsers(groupId, level, da);
541        return result;
542      }
543      catch(Exception e) {
544        setRollbackOnly();
545        throw new InstantbankException(e, "131011", "Failed to retrieve children groups");
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 String getChildUsers(Long groupId, int level, XMLDataAccess da) throws InstantbankException {
560      String Groups;
561      XMLDocument doc;
562      XMLDocument docChild;
563      NodeList nlChild;
564      int nlChlLen;
565      XMLNode nodeChild;
566      XMLElement ParElement;
567      String responseXml = new String();
568      String sql;
569      String UserGrpId;
570      String xml = new String();
571      ;
572  
573      try {
574        if((new Long(level)).equals(new Long(1))) {
575          sql = "SELECT user_id id, user_userid userid, user_first_name||' '||user_last_name name, user_status_flag status FROM users WHERE user_usg_id=" + groupId;
576          docChild = da.makeXMLSelect(sql, "ChildUsers", "User");
577          ParElement = (XMLElement)docChild.getDocumentElement();
578          StringWriter sw = new StringWriter();
579          PrintWriter pw = new PrintWriter(sw);
580          ParElement.print(pw);
581          xml = sw.toString();
582        }
583        else {
584          Groups = getChildGroups(groupId, level, da);
585          doc = parseInfo(Groups);
586          nlUserGroupsId = doc.selectNodes("/ChildGroups/Group/id/text()");
587          nlUserGroupsLen = nlUserGroupsId.getLength();
588          for(int i = 0; i < nlUserGroupsLen; i++) {
589            UserGrpId = nlUserGroupsId.item(i).getNodeValue();
590            sql = "SELECT user_id id, user_userid userid, user_first_name||' '||user_last_name name, user_status_flag status FROM users WHERE user_usg_id=" + UserGrpId;
591            docChild = da.makeXMLSelect(sql, "ChildUsers", "User");
592            ParElement = (XMLElement)docChild.getDocumentElement();
593            StringWriter sw = new StringWriter();
594            PrintWriter pw = new PrintWriter(sw);
595            ParElement.print(pw);
596            xml = xml + sw.toString();
597          }
598        }
599        return xml;
600      }
601      catch(Exception e) {
602        setRollbackOnly();
603        throw new InstantbankException(e, "131009", "Failed to retrieve children users");
604      }
605    }
606  
607  
608    private String getChildUsers(Long groupId, Long supervisorId, String objectType, DataAccess da) throws InstantbankException {
609      boolean header;
610      String sql;
611      Long userId;
612      ResultSet userList = null;
613      String userName;
614      String userNumber;
615      String userStatus;
616      Statement st = null;
617      String xml;
618  
619      try {
620        st = da.getConnection().createStatement();
621        // Finds the users at the first level of the group
622        sql = "SELECT ";
623        sql += "user_id id, ";
624        sql += "user_userid userid, ";
625        sql += "user_first_name||' '||user_last_name name, ";
626        sql += "user_status_flag status ";
627        sql += "FROM ";
628        sql += "users ";
629        sql += "WHERE ";
630        sql += "user_usg_id=" + groupId;
631        userList = st.executeQuery(sql);
632  
633        header = false;
634        xml = "";
635        while(userList.next()) {
636          userId = new Long(userList.getLong(1));
637          userNumber = userList.getString(2);
638          userName = userList.getString(3);
639          userStatus = userList.getString(4);
640          if(isUserSupervisedBy(userId, supervisorId, objectType, da)) {
641            if(!header) {
642              xml = "<ChildUsers>";
643              header = true;
644            }
645            xml += "<User>";
646            xml += "<id>" + userId + "</id>";
647            xml += "<userid>" + userNumber + "</userid>";
648            xml += "<name>" + userName + "</name>";
649            xml += "<status>" + userStatus + "</status>";
650            xml += "</User>";
651          }
652        }
653        if(header) {
654          xml += "</ChildUsers>";
655        }
656        return xml;
657      }
658      catch(Exception e) {
659        setRollbackOnly();
660        throw new InstantbankException(e, "131033", "Failed to retrieve children groups and users for supervisor " + supervisorId);
661      }
662      finally {
663        try {
664          if(userList != null) {
665            userList.close();
666          }
667          if(st != null) {
668            st.close();
669          }
670  
671        }
672        catch(Exception e) {
673        }
674      }
675    }
676  
677  
678    public String getGroup(Long groupId) throws InstantbankException {
679      String sql;
680      XMLDataAccess da = null;
681  
682      try {
683        da = new XMLDataAccess("");
684        da.connect();
685        sql = "SELECT usg_id id, usg_name name, NVL(user_userid, '_') changedby, NVL(to_char(usg_last_changed_date, 'MM-DD-YYYY'), '_') changeddate FROM user_groups, users WHERE usg_id=" + groupId +
686          " AND usg_last_changed_by = user_id(+)";
687        return da.getXml(sql, "GroupList", "Group");
688      }
689      catch(Exception e) {
690        setRollbackOnly();
691        throw new InstantbankException(e, "131034", "Failed to get group " + groupId);
692      }
693      finally {
694        try {
695          if(da != null) {
696            da.disconnect();
697          }
698        }
699        catch(Exception e) {
700        }
701      }
702    }
703  
704  
705    public String getGroups(Long companyId) throws InstantbankException {
706      XMLDataAccess da = null;
707      XMLDocument doc;
708      String ResPar = new String();
709      String sql;
710      String xml;
711  
712      try {
713        da = new XMLDataAccess("");
714        da.connect();
715        sql = "SELECT usg_id id, usg_name name, usg_sprf_id profileid, NVL(user_userid, '_') changedby, NVL(to_char(usg_last_changed_date, 'MM-DD-YYYY'), '_') changeddate FROM user_groups, users WHERE usg_cmp_id=" + companyId + " and usg_parent_id is null" +
716          " AND usg_last_changed_by = user_id(+)";
717        doc = da.makeXMLSelect(sql, "GroupList", "Group");
718        nlIdParent = doc.selectNodes("/GroupList/Group/id/text()");
719        nlNameParent = doc.selectNodes("/GroupList/Group/name/text()");
720        nlProfileParent = doc.selectNodes("/GroupList/Group/profileid/text()");
721        nlByParent = doc.selectNodes("/GroupList/Group/changedby/text()");
722        nlDateParent = doc.selectNodes("/GroupList/Group/changeddate/text()");
723        nlLength = nlIdParent.getLength();
724        for(int k = 0; k < nlLength; k++) {
725          IdParent = new Long(nlIdParent.item(k).getNodeValue());
726          NameParent = nlNameParent.item(k).getNodeValue();
727          ProfileParent = nlProfileParent.item(k).getNodeValue();
728          ByParent = nlByParent.item(k).getNodeValue();
729          DateParent = nlDateParent.item(k).getNodeValue();
730          Children = getChildGroups(IdParent, 0, da);
731          Parent = Parent + makeXMLAttributes("id", IdParent.toString());
732          Parent = Parent + makeXMLAttributes("name", NameParent);
733          Parent = Parent + makeXMLAttributes("profileid", ProfileParent);
734          Parent = Parent + makeXMLAttributes("changedby", ByParent);
735          Parent = Parent + makeXMLAttributes("changeddate", DateParent);
736          Parent = Parent + Children;
737          ResPar = ResPar + makeXMLElement("Group", Parent);
738        }
739        ResPar = makeXMLNode("GroupList", ResPar, true);
740        return ResPar;
741      }
742      catch(Exception e) {
743        setRollbackOnly();
744        throw new InstantbankException(e, "131035", "Failed to retrieve groups");
745      }
746      finally {
747        try {
748          if(da != null) {
749            da.disconnect();
750          }
751        }
752        catch(Exception e) {
753        }
754      }
755    }
756  
757  
758    public String getGroupsUsers(Long companyId) throws InstantbankException {
759      XMLDataAccess da = null;
760      XMLDocument doc;
761      Long grpId;
762      String ResPar = new String();
763      String sql;
764      String xml;
765      String xmlUser;
766  
767      try {
768        da = new XMLDataAccess("");
769        da.connect();
770        sql = "SELECT usg_id id, usg_name name FROM user_groups ";
771        sql += "WHERE usg_cmp_id=" + companyId + " and usg_parent_id is null";
772        doc = da.makeXMLSelect(sql, "GroupList", "Group");
773        nlIdParent = doc.selectNodes("/GroupList/Group/id/text()");
774        nlNameParent = doc.selectNodes("/GroupList/Group/name/text()");
775        nlLength = nlIdParent.getLength();
776        for(int k = 0; k < nlLength; k++) {
777          grpId = IdParent = new Long(nlIdParent.item(k).getNodeValue());
778          NameParent = nlNameParent.item(k).getNodeValue();
779          xmlUser = getChildUsers(grpId, 1, da);
780          Children = getChildGroupsUsers(IdParent, 0, da);
781          Parent = Parent + makeXMLAttributes("id", IdParent.toString());
782          Parent = Parent + makeXMLAttributes("name", NameParent);
783          Parent = Parent + xmlUser;
784          Parent = Parent + Children;
785          ResPar = ResPar + makeXMLElement("Group", Parent);
786        }
787        ResPar = makeXMLNode("GroupList", ResPar, true);
788        return ResPar;
789      }
790      catch(Exception e) {
791        setRollbackOnly();
792        throw new InstantbankException(e, "131036", "Failed to retrieve group hierarchy");
793      }
794      finally {
795        try {
796          if(da != null) {
797            da.disconnect();
798          }
799        }
800        catch(Exception e) {
801        }
802      }
803    }
804  
805  
806    public String getGroupsUsers(Long companyId, Long supervisorId, String objectType) throws InstantbankException {
807      DataAccess da = null;
808      ResultSet groupList = null;
809      Long groupId;
810      String groupName;
811      Statement st = null;
812      String sql;
813      ResultSet user = null;
814      String xml;
815      String xmlGroups;
816      String xmlUsers;
817  
818      try {
819        da = new DataAccess();
820        da.connect();
821        st = da.getConnection().createStatement();
822  
823        xml = XMLUtils.xmlHeader();
824        xml += "<GroupList>";
825  
826        sql = "SELECT ";
827        sql += "user_id id, ";
828        sql += "user_userid userid, ";
829        sql += "user_first_name||' '||user_last_name name, ";
830        sql += "user_status_flag status ";
831        sql += "FROM ";
832        sql += "users ";
833        sql += "WHERE ";
834        sql += "(user_id = " + supervisorId + ")";
835        user = st.executeQuery(sql);
836        if(!user.next()) {
837          throw new InstantbankException("131040", "Supervisor not found");
838        }
839        xml += "<Supervisor>";
840        xml += "<id>" + user.getString("id") + "</id>";
841        xml += "<userid>" + user.getString("userid") + "</userid>";
842        xml += "<name>" + user.getString("name") + "</name>";
843        xml += "<status>" + user.getString("status") + "</status>";
844        xml += "</Supervisor>";
845  
846        // Finds the first level groups
847        sql = "SELECT ";
848        sql += "usg_id id, usg_name name ";
849        sql += "FROM ";
850        sql += "user_groups ";
851        sql += "WHERE ";
852        sql += "usg_cmp_id=" + companyId + " and usg_parent_id is null";
853        groupList = st.executeQuery(sql);
854  
855        while(groupList.next()) {
856          groupId = new Long(groupList.getLong(1));
857          groupName = groupList.getString(2);
858          if(isGroupSupervisedBy(groupId, supervisorId, objectType, da)) {
859            xmlUsers = getChildUsers(groupId, new Long(0), objectType, da);
860            xmlGroups = getChildGroupsUsers(groupId, 0, new Long(0), objectType, da);
861          }
862          else {
863            xmlUsers = getChildUsers(groupId, supervisorId, objectType, da);
864            xmlGroups = getChildGroupsUsers(groupId, 0, supervisorId, objectType, da);
865          }
866          if(!xmlUsers.equals("") || !xmlGroups.equals("")) {
867            xml += "<Group>";
868            xml += "<id>" + groupId + "</id>";
869            xml += "<name>" + groupName + "</name>";
870            xml += xmlUsers;
871            xml += xmlGroups;
872            xml += "</Group>";
873          }
874        }
875        xml += "</GroupList>";
876        return xml;
877      }
878      catch(Exception e) {
879        setRollbackOnly();
880        throw new InstantbankException(e, "131037", "Failed to retrieve children groups and users for supervisor " + supervisorId);
881      }
882      finally {
883        try {
884          if(user != null) {
885            user.close();
886          }
887          if(groupList != null) {
888            groupList.close();
889          }
890          if(st != null) {
891            st.close();
892          }
893          if(da != null) {
894            da.disconnect();
895          }
896        }
897        catch(Exception e) {
898        }
899      }
900    }
901  
902  
903    public String getSessionInfo(String pUserName) throws InstantbankException {
904      String companyNumber;
905      XMLDataAccess da;
906      XMLDocument doc;
907      int pUnderScore;
908      String sql;
909      String userName;
910      String xml;
911  
912      try {
913        if(pUserName.lastIndexOf(new String(":")) != -1) {
914          pUnderScore = pUserName.lastIndexOf(new String(":"));
915          userName = pUserName.substring(0, pUnderScore);
916          companyNumber = pUserName.substring(pUnderScore + 1, pUserName.length());
917        }
918        else {
919          userName = pUserName;
920          companyNumber = "";
921        }
922        da = new XMLDataAccess("");
923        sql =
924          "select " +
925          "user_cmp_id companyid, cmp_name companyname, user_id userid, " +
926          "user_first_name||' '||user_last_name username, user_usg_id groupid, " +
927          "csp_order_letter orderletter, csp_action_code_level actioncode, " +
928          "csp_result_code_level resultcode, user_status_flag status " +
929          "from " +
930          "users, companies, user_groups, security_profiles, collections_security_profiles " +
931          "where " +
932          "user_cmp_id = cmp_id(+) and user_usg_id = usg_id(+) and " +
933          "user_sprf_id = sprf_id and sprf_csp_id = csp_id and " +
934          "user_userid = '" + userName + "' and " +
935          "cmp_number = '" + companyNumber + "'";
936        da.connect();
937        doc = da.makeXMLSelect(sql, "Session", "");
938        StringWriter sw = new StringWriter();
939        PrintWriter pw = new PrintWriter(sw);
940        doc.print(pw);
941        da.disconnect();
942        return sw.toString();
943      }
944      catch(Exception e) {
945        setRollbackOnly();
946        throw new InstantbankException(e, "131013", "Failed to get session data");
947      }
948    }
949  
950  
951    public String getSysdate(String format) throws InstantbankException {
952      Connection con = null;
953      PreparedStatement ps = null;
954      ResultSet result = null;
955      String sysdate = null;
956      try {
957        con = ServiceLocator.instance().getConnection();
958        ps = con.prepareStatement("SELECT to_char(sysdate, '" + format + "') today FROM dual");
959        result = ps.executeQuery();
960        if(result.next()) {
961          sysdate = result.getString("today");
962        }
963        return sysdate;
964      }
965      catch(Exception e) {
966        setRollbackOnly();
967        throw new InstantbankException(e, "131014", "Failed to get system date");
968      }
969      finally {
970        try {
971          if(result != null) {
972            result.close();
973          }
974          if(ps != null) {
975            ps.close();
976          }
977          if(con != null) {
978            con.close();
979          }
980        }
981        catch(SQLException se) {
982        }
983      }
984    }
985  
986  
987    public String getUser(Long userId) throws InstantbankException {
988      String xml;
989      String sql;
990      XMLDataAccess da = null;
991      XMLDocument doc;
992  
993      try {
994        da = new XMLDataAccess("");
995        da.connect();
996        sql = "SELECT ";
997        sql += "users.user_id id, ";
998        sql += "users.user_userid userid, ";
999        sql += "users.user_first_name firstname, ";
1000       sql += "users.user_last_name lastname, ";
1001       sql += "users.user_alias alias, ";
1002       sql += "nvl(to_char(users.user_date_last_logon, 'MM-DD-YYYY'), '_') datelastlogon, ";
1003       sql += "users.user_phone phone, ";
1004       sql += "nvl(to_char(users.user_extension), '_') extension, ";
1005       sql += "users.user_email email, ";
1006       sql += "nvl(to_char(users.user_date_pwd_created, 'MM-DD-YYYY'), '_') datepwdcreated, ";
1007       sql += "users.user_current_sign_on_attempts currentsingonattempts, ";
1008       sql += "users.user_status_flag statusflag, ";
1009       sql += "users.user_time_offset timeoffset, ";
1010       sql += "nvl(users.user_title, '_') title, ";
1011       sql += "nvl(to_char(users.user_last_changed_by), '_') lastchangedbyid, ";
1012       sql += "changed_by.user_userid lastchangedbyname, ";
1013       sql += "nvl(to_char(users.user_last_changed_date, 'MM-DD-YYYY'), '_') lastchangeddate, ";
1014       sql += "users.user_usg_id groupid, ";
1015       sql += "users.user_sprf_id profileid	";
1016       sql += "FROM ";
1017       sql += " users, ";
1018       sql += " users changed_by	";
1019       sql += "WHERE	";
1020       sql += "users.user_id = " + userId + " and	";
1021       sql += "changed_by.user_id(+) = users.user_last_changed_by ";
1022       return da.getXml(sql, "UserList", "User");
1023     }
1024     catch(Exception e) {
1025       setRollbackOnly();
1026       throw new InstantbankException(e, "131015", "Failed to get the user " + userId);
1027     }
1028     finally {
1029       try {
1030         if(da != null) {
1031           da.disconnect();
1032         }
1033       }
1034       catch(Exception e) {
1035       }
1036     }
1037   }
1038 
1039 
1040   public String getUserPassword(Long userId) throws InstantbankException {
1041     Connection con = null;
1042     PreparedStatement ps = null;
1043     ResultSet result = null;
1044     String xml = "";
1045     String oldPassword;
1046     String sql;
1047 
1048     try {
1049       sql = "select user_password from users where user_id = ? ";
1050       con = ServiceLocator.instance().getConnection();
1051       ps = con.prepareStatement(sql);
1052       ps.setLong(1, userId.longValue());
1053       result = ps.executeQuery();
1054 
1055       if(result.next()) {
1056         oldPassword = new String(result.getString(1));
1057       }
1058       else {
1059         oldPassword = new String("");
1060       }
1061 
1062       return oldPassword;
1063     }
1064     catch(Exception e) {
1065       throw new InstantbankException(e, "131009", "Failed to get the the user password");
1066     }
1067     finally {
1068       try {
1069         if(result != null) {
1070           result.close();
1071         }
1072         if(ps != null) {
1073           ps.close();
1074         }
1075         if(con != null) {
1076           con.close();
1077         }
1078       }
1079       catch(SQLException se) {
1080         se.printStackTrace();
1081       }
1082     }
1083 
1084   }
1085 
1086 
1087   public String getUserProfileId(String userId) throws InstantbankException {
1088     Connection con = null;
1089     PreparedStatement ps = null;
1090     ResultSet result = null;
1091     String PrfId = null;
1092     try {
1093       con = ServiceLocator.instance().getConnection();
1094       ps = con.prepareStatement("SELECT user_sprf_id FROM users WHERE user_id = ?");
1095       ps.setString(1, userId);
1096       result = ps.executeQuery();
1097       if(result.next()) {
1098         PrfId = result.getString("user_sprf_id");
1099       }
1100       return PrfId;
1101     }
1102     catch(Exception e) {
1103       setRollbackOnly();
1104       throw new InstantbankException(e, "131016", "Failed to retrieve profile for the user " + userId);
1105     }
1106     finally {
1107       try {
1108         if(result != null) {
1109           result.close();
1110         }
1111         if(ps != null) {
1112           ps.close();
1113         }
1114         if(con != null) {
1115           con.close();
1116         }
1117       }
1118       catch(SQLException se) {
1119       }
1120     }
1121   }
1122 
1123 
1124   public String getUsers(Long companyId) throws InstantbankException {
1125     XMLDataAccess da = null;
1126     String sql;
1127 
1128     try {
1129       da = new XMLDataAccess("");
1130       da.connect();
1131       sql = "select user_id id, user_userid userid, user_first_name||' '||user_last_name name, user_alias alias " +
1132         "from users where user_cmp_id = " + companyId + " order by name";
1133       return da.getXml(sql, "UserList", "User");
1134     }
1135     catch(Exception e) {
1136       setRollbackOnly();
1137       throw new InstantbankException(e, "131017", "Failed to retrieve users");
1138     }
1139     finally {
1140       try {
1141         if(da != null) {
1142           da.disconnect();
1143         }
1144       }
1145       catch(Exception e) {
1146       }
1147     }
1148   }
1149 
1150 
1151   private boolean isGroupSupervisedBy(Long groupId, Long supervisorId, String objectType, DataAccess da) throws InstantbankException {
1152     ResultSet result = null;
1153     Statement st = null;
1154     String sql;
1155     String sqlQueues;
1156 
1157     if(supervisorId.longValue() == 0) {
1158       return true;
1159     }
1160     try {
1161       st = da.getConnection().createStatement();
1162       sqlQueues = "SELECT DISTINCT qpu_qplan_id queueId FROM queue_plan_users WHERE qpu_user_id=" + supervisorId;
1163       if(objectType.equals("A")) {
1164         sql = "SELECT usg_id FROM ";
1165         sql += "user_groups,";
1166         sql += "security_profiles,";
1167         sql += "collections_security_profiles ";
1168         sql += "WHERE ";
1169         sql += "(usg_id = " + groupId + ") AND ";
1170         sql += "(sprf_id (+)= usg_sprf_id) AND ";
1171         sql += "(csp_id (+)= sprf_csp_id) AND ";
1172         sql += "(csp_supervisor_queue_id IN (" + sqlQueues + "))";
1173         result = st.executeQuery(sql);
1174         if(result.next()) {
1175           return true;
1176         }
1177       }
1178       return false;
1179     }
1180     catch(Exception e) {
1181       throw new InstantbankException(e, "131038", "Failed checking if group is supervised by " + supervisorId);
1182     }
1183     finally {
1184       try {
1185         if(result != null) {
1186           result.close();
1187         }
1188         if(st != null) {
1189           st.close();
1190         }
1191 
1192       }
1193       catch(Exception e) {
1194       }
1195     }
1196   }
1197 
1198 
1199   private boolean isUserSupervisedBy(Long userId, Long supervisorId, String objectType, DataAccess da) throws InstantbankException {
1200     ResultSet result = null;
1201     Statement st = null;
1202     String sql;
1203     String sqlQueues;
1204 
1205     if(supervisorId.longValue() == 0) {
1206       return true;
1207     }
1208     try {
1209       st = da.getConnection().createStatement();
1210       sqlQueues = "SELECT DISTINCT qpu_qplan_id queueId FROM queue_plan_users WHERE qpu_user_id=" + supervisorId;
1211       if(objectType.equals("A")) {
1212         sql = "SELECT user_id FROM ";
1213         sql += "users,";
1214         sql += "security_profiles,";
1215         sql += "collections_security_profiles ";
1216         sql += "WHERE ";
1217         sql += "(user_id = " + userId + ") AND ";
1218         sql += "(sprf_id (+)= user_sprf_id) AND ";
1219         sql += "(csp_id (+)= sprf_csp_id) AND ";
1220         sql += "(csp_supervisor_queue_id IN (" + sqlQueues + "))";
1221         result = st.executeQuery(sql);
1222         if(result.next()) {
1223           return true;
1224         }
1225       }
1226       return false;
1227     }
1228     catch(Exception e) {
1229       throw new InstantbankException(e, "131039", "Failed checking if user is supervised by " + supervisorId);
1230     }
1231     finally {
1232       try {
1233         if(result != null) {
1234           result.close();
1235         }
1236         if(st != null) {
1237           st.close();
1238         }
1239 
1240       }
1241       catch(Exception e) {
1242       }
1243     }
1244   }
1245 
1246 
1247   private String makeXMLAttributes(String attributeNode, String valueNode) {
1248     String XMLtmp = new String();
1249     char Ch3 = '/';
1250     valueNode = StringFormat.toSafeXMLString(valueNode);
1251     XMLtmp = "<" + attributeNode + ">" + valueNode + "<" + Ch3 + attributeNode + ">\n";
1252     return XMLtmp;
1253   }
1254 
1255 
1256   private String makeXMLElement(String element, String XMLAttributes) {
1257     String XMLtmp = new String();
1258     char Ch3 = '/';
1259     XMLtmp = "<" + element + ">\n" + XMLAttributes +
1260       "<" + Ch3 + element + ">\n";
1261     return XMLtmp;
1262   }
1263 
1264 
1265   private String makeXMLNode(
1266                              String nameNode,
1267                              String XMLElement,
1268                              boolean withHeader
1269                              ) {
1270     String XMLtmp = new String();
1271     char Ch3 = '/';
1272     char Ch1 = '"';
1273     if(withHeader) {
1274       XMLtmp = XMLUtils.xmlHeader() + "\n";
1275     }
1276     else {
1277       XMLtmp = "";
1278     }
1279     XMLtmp = XMLtmp + "<" + nameNode + "> \n" + XMLElement + "<" + Ch3 + nameNode + ">\n";
1280     return XMLtmp;
1281   }
1282 
1283 
1284   private void modifyPassword(long UsrId)
1285      throws InstantbankException {
1286     Connection con = null;
1287     PreparedStatement ps = null;
1288     ResultSet result = null;
1289     try {
1290       con = ServiceLocator.instance().getConnection();
1291       ps = con.prepareStatement(
1292         "update users set " +
1293         "user_password = user_userid, " +
1294         "user_last_changed_by = ?, " +
1295         "user_last_changed_date = sysdate, " +
1296         "user_status_flag = 3, " +
1297         "user_current_sign_on_attempts = 0 " +
1298         "where user_id = ?"
1299         );
1300       ps.setLong(1, lastChangedBy.longValue());
1301       ps.setLong(2, UsrId);
1302 
1303       int n = ps.executeUpdate();
1304       if(n != 1) {
1305         throw new InstantbankException("131018", "Failed to modify Users to the database");
1306       }
1307     }
1308     catch(Exception e) {
1309       setRollbackOnly();
1310       throw new InstantbankException(e, "131019", "Failed to modify Users to the database");
1311     }
1312     finally {
1313       try {
1314         if(ps != null) {
1315           ps.close();
1316         }
1317         if(con != null) {
1318           con.close();
1319         }
1320       }
1321       catch(SQLException se) {
1322         se.printStackTrace();
1323       }
1324     }
1325   }
1326 
1327 
1328   private void modifyUser(
1329                           XMLDocument User,
1330                           long UsrId,
1331                           long companyId,
1332                           long prfId
1333                           ) throws InstantbankException {
1334     Connection con = null;
1335     PreparedStatement ps = null;
1336     ResultSet result = null;
1337     try {
1338       con = ServiceLocator.instance().getConnection();
1339       ps = con.prepareStatement(
1340         "update users set " +
1341         "user_cmp_id = ?, " +
1342         "user_usg_id = ?, " +
1343         "user_sprf_id = ?, " +
1344         "user_alias = ?, " +
1345         "user_first_name = ?, " +
1346         "user_last_name = ?, " +
1347         "user_last_changed_by = ?, " +
1348         "user_last_changed_date = sysdate, " +
1349         "user_phone = ?, " +
1350         "user_extension = ?, " +
1351         "user_email = ?, " +
1352         "user_status_flag = ?, " +
1353         "user_time_offset = ?, " +
1354         "user_title = ?, " +
1355         "user_userid = ?, " +
1356         "user_company_level_id = ?, " +
1357         "user_portafolio_level_id = ?, " +
1358         "user_legal_level_id = ?, " +
1359         "user_inactive_code = ? " +
1360         "where user_id = ?"
1361         );
1362       ps.setLong(1, companyId);
1363       ps.setLong(2, Long.parseLong(User.valueOf("/UserList/User/groupid")));
1364       ps.setLong(3, prfId);
1365       ps.setString(4, User.valueOf("/UserList/User/alias"));
1366       ps.setString(5, User.valueOf("/UserList/User/firstname"));
1367       ps.setString(6, User.valueOf("/UserList/User/lastname"));
1368       ps.setLong(7, lastChangedBy.longValue());
1369       ps.setString(8, User.valueOf("/UserList/User/phone"));
1370       if(User.valueOf("/UserList/User/extension").equals("_")) {
1371         ps.setNull(9, java.sql.Types.VARCHAR);
1372       }
1373       else {
1374         ps.setString(9, User.valueOf("/UserList/User/extension"));
1375       }
1376       ps.setString(10, User.valueOf("/UserList/User/email"));
1377       ps.setLong(11, Long.parseLong(User.valueOf("/UserList/User/statusflag")));
1378       ps.setLong(12, Long.parseLong(User.valueOf("/UserList/User/timeoffset")));
1379       if(User.valueOf("/UserList/User/title").equals("_")) {
1380         ps.setNull(13, java.sql.Types.VARCHAR);
1381       }
1382       else {
1383         ps.setString(13, User.valueOf("/UserList/User/title"));
1384       }
1385       ps.setString(14, User.valueOf("/UserList/User/userid"));
1386       ps.setNull(15, java.sql.Types.NUMERIC);
1387       ps.setNull(16, java.sql.Types.NUMERIC);
1388       ps.setNull(17, java.sql.Types.NUMERIC);
1389       ps.setNull(18, java.sql.Types.NUMERIC);
1390       ps.setLong(19, UsrId);
1391 
1392       int n = ps.executeUpdate();
1393 
1394       if(n != 1) {
1395         throw new InstantbankException("131020", "Failed to modify Users to the database");
1396       }
1397     }
1398     catch(Exception e) {
1399       setRollbackOnly();
1400       throw new InstantbankException(e, "131021", "Failed to modify Users to the database");
1401     }
1402     finally {
1403       try {
1404         if(ps != null) {
1405           ps.close();
1406         }
1407         if(con != null) {
1408           con.close();
1409         }
1410       }
1411       catch(SQLException se) {
1412         se.printStackTrace();
1413       }
1414     }
1415   }
1416 
1417 
1418   private void modifyUserGroup(
1419                                XMLDocument Groups,
1420                                long groupId,
1421                                long companyId,
1422                                long prfId
1423                                ) throws InstantbankException {
1424     Connection con = null;
1425     PreparedStatement ps = null;
1426     ResultSet result = null;
1427     try {
1428       con = ServiceLocator.instance().getConnection();
1429       ps = con.prepareStatement(
1430         "update user_groups set " +
1431         "usg_parent_id = ?, " +
1432         "usg_sprf_id = ?, " +
1433         "usg_name = ?, " +
1434         "usg_last_changed_by = ?, " +
1435         "usg_last_changed_date = sysdate " +
1436         "where usg_id = ?"
1437         );
1438       if(Groups.valueOf("/GroupList/Group/parentid").equals("_")) {
1439         ps.setNull(1, java.sql.Types.NUMERIC);
1440       }
1441       else {
1442         ps.setLong(1, Long.parseLong(Groups.valueOf("/GroupList/Group/parentid")));
1443       }
1444       ps.setLong(2, prfId);
1445       ps.setString(3, Groups.valueOf("/GroupList/Group/name"));
1446       ps.setLong(4, lastChangedBy.longValue());
1447       ps.setLong(5, groupId);
1448 
1449       int n = ps.executeUpdate();
1450       if(n != 1) {
1451         throw new InstantbankException("131022", "Failed to Modify User Groups to the database");
1452       }
1453     }
1454     catch(Exception e) {
1455       setRollbackOnly();
1456       throw new InstantbankException(e, "131023", "Failed to Modify User Groups to the database");
1457     }
1458     finally {
1459       try {
1460         if(ps != null) {
1461           ps.close();
1462         }
1463         if(con != null) {
1464           con.close();
1465         }
1466       }
1467       catch(SQLException se) {
1468         se.printStackTrace();
1469       }
1470     }
1471   }
1472 
1473 
1474   public String newGroup() throws InstantbankException {
1475     String doc;
1476 
1477     doc = "";
1478     doc = doc + makeXMLAttributes("id", "0");
1479     doc = doc + makeXMLAttributes("name", "_");
1480     doc = doc + makeXMLAttributes("profileid", "_");
1481     doc = doc + makeXMLAttributes("changedby", "_");
1482     doc = doc + makeXMLAttributes("changeddate", "_");
1483     doc = makeXMLElement("Group", doc);
1484     doc = makeXMLNode("GroupList", doc, true);
1485     return doc;
1486   }
1487 
1488 
1489   public String newUser() throws InstantbankException {
1490     String doc;
1491 
1492     doc = "";
1493     doc = doc + makeXMLAttributes("id", "0");
1494     doc = doc + makeXMLAttributes("userid", "_");
1495     doc = doc + makeXMLAttributes("firstname", "_");
1496     doc = doc + makeXMLAttributes("lastname", "_");
1497     doc = doc + makeXMLAttributes("alias", "_");
1498     doc = doc + makeXMLAttributes("datelastlogon", "_");
1499     doc = doc + makeXMLAttributes("phone", "_");
1500     doc = doc + makeXMLAttributes("extension", "_");
1501     doc = doc + makeXMLAttributes("email", "_");
1502     doc = doc + makeXMLAttributes("datepwdcreated", "_");
1503     doc = doc + makeXMLAttributes("currentsingonattempts", "_");
1504     doc = doc + makeXMLAttributes("statusflag", "_");
1505     doc = doc + makeXMLAttributes("timeoffset", "_");
1506     doc = doc + makeXMLAttributes("title", "_");
1507     doc = doc + makeXMLAttributes("lastchangedbyid", "_");
1508     doc = doc + makeXMLAttributes("lastchangedbyname", "_");
1509     doc = doc + makeXMLAttributes("lastchangeddate", "_");
1510     doc = doc + makeXMLAttributes("groupid", "_");
1511     doc = doc + makeXMLAttributes("profileid", "0");
1512     doc = makeXMLElement("User", doc);
1513     doc = makeXMLNode("UserList", doc, true);
1514     return doc;
1515   }
1516 
1517 
1518   private XMLDocument parseInfo(String data) throws XSLException, InstantbankException {
1519     DOMParser docParser = new DOMParser();
1520     ByteArrayInputStream stream;
1521     XMLDocument xmlDoc;
1522 
1523     xmlDoc = null;
1524     try {
1525       stream = new ByteArrayInputStream(data.getBytes());
1526       docParser.setValidationMode(false);
1527       docParser.parse(stream);
1528       xmlDoc = docParser.getDocument();
1529       return xmlDoc;
1530     }
1531     catch(Exception e) {
1532       setRollbackOnly();
1533       throw new InstantbankException(e, "131024", "Failed to parse a XML document");
1534     }
1535   }
1536 
1537 
1538   public void resetAllPassword(Long companyId, Long changedBy) throws InstantbankException {
1539     DataAccess da = null;
1540     ResultSet rs = null;
1541     Statement st = null;
1542     Long userId;
1543     String dataQuery;
1544     try {
1545       da = new DataAccess();
1546       da.connect();
1547       st = da.getConnection().createStatement();
1548       dataQuery = "SELECT ";
1549       dataQuery += "USER_ID ";
1550       dataQuery += "FROM ";
1551       dataQuery += "users ";
1552       dataQuery += "WHERE ";
1553       dataQuery += "USER_CMP_ID =" + companyId;
1554       rs = st.executeQuery(dataQuery);
1555       while(rs.next()) {
1556         userId = new Long(rs.getLong(1));
1557         resetUserPassword(userId.longValue(), changedBy);
1558       }
1559     }
1560     catch(Exception e) {
1561       setRollbackOnly();
1562       throw new InstantbankException(e, "131028", "Failed to reset all passwords for Company");
1563     }
1564     finally {
1565       try {
1566         if(rs != null) {
1567           rs.close();
1568         }
1569         if(st != null) {
1570           st.close();
1571         }
1572         if(da != null) {
1573           da.disconnect();
1574         }
1575       }
1576       catch(Exception e) {}
1577     }
1578   }
1579 
1580 
1581   public void resetUserPassword(long userId, Long changedBy)
1582      throws InstantbankException {
1583     try {
1584       long uppId = UniqueIDGenerator.instance().getNextId();
1585       lastChangedBy = changedBy;
1586       createPreviousPwd(uppId, userId);
1587       modifyPassword(userId);
1588     }
1589     catch(Exception e) {
1590       setRollbackOnly();
1591       throw new InstantbankException(e, "131025", "Failed to reset password for user " + userId);
1592     }
1593   }
1594 
1595 
1596   public void saveGroup(String data, String profile, Long companyId, Long changedBy) throws InstantbankException {
1597     String groupId = new String();
1598     long prfId;
1599     XMLDocument XMLData;
1600 
1601     try {
1602       prfId = saveProfiles(profile, companyId);
1603       lastChangedBy = changedBy;
1604       long GrpId = UniqueIDGenerator.instance().getNextId();
1605       XMLData = parseInfo(data);
1606       groupId = XMLData.valueOf("/GroupList/Group/id");
1607       if(groupId.equals("0")) {
1608         createUserGroup(XMLData, GrpId, companyId.longValue(), prfId);
1609       }
1610       else {
1611         modifyUserGroup(XMLData, Long.parseLong(groupId), companyId.longValue(), prfId);
1612       }
1613     }
1614     catch(Exception e) {
1615       setRollbackOnly();
1616       throw new InstantbankException(e, "131026", "Failed to save group");
1617     }
1618   }
1619 
1620 
1621   private long saveProfiles(String profile, Long companyId) throws NamingException, SQLException, RemoteException, Exception {
1622     long hostId;
1623     long prfId;
1624     SecurityProfilesServices pservices;
1625     String sql;
1626 
1627     // find id of hosting company
1628     Connection con = ServiceLocator.instance().getConnection();
1629     sql = "SELECT HostCompany FROM DUAL";
1630     PreparedStatement ps = con.prepareStatement(sql);
1631     ResultSet rs = ps.executeQuery();
1632     if(rs.next()) {
1633       hostId = rs.getLong(1);
1634     }
1635     else {
1636       hostId = 0;
1637     }
1638     SecurityProfilesServicesHome phome = (SecurityProfilesServicesHome)
1639       ServiceLocator.instance().createEJB("SecurityProfilesServicesHome", SecurityProfilesServicesHome.class, true);
1640     pservices = phome.create();
1641     prfId = pservices.saveProfiles(profile, (companyId.longValue() == hostId));
1642     return prfId;
1643   }
1644 
1645 
1646   public void saveUser(String data, String profile, Long companyId, Long changedBy) throws InstantbankException {
1647     long prfId;
1648     String userId = new String();
1649     XMLDocument XMLData;
1650 
1651     try {
1652       prfId = saveProfiles(profile, companyId);
1653       lastChangedBy = changedBy;
1654       long UsrId = UniqueIDGenerator.instance().getNextId();
1655       XMLData = parseInfo(data);
1656       userId = XMLData.valueOf("/UserList/User/id");
1657       if(userId.equals("0")) {
1658         createUser(XMLData, UsrId, companyId.longValue(), prfId);
1659       }
1660       else {
1661         modifyUser(XMLData, Long.parseLong(userId), companyId.longValue(), prfId);
1662       }
1663     }
1664     catch(Exception e) {
1665       setRollbackOnly();
1666       throw new InstantbankException(e, "131027", "Failed to save user");
1667     }
1668   }
1669 
1670 
1671   public SecurityServicesBean() { }
1672 
1673 
1674   private void setRollbackOnly() {
1675     try {
1676       this.context.setRollbackOnly();
1677     }
1678     catch(Exception e) {
1679     }
1680   }
1681 
1682 
1683   public void setSessionContext(SessionContext ctx) {
1684     this.context = ctx;
1685   }
1686 
1687 
1688   public void setSessionSuccessfull(Long userId) throws InstantbankException {
1689     Connection con = null;
1690     PreparedStatement ps = null;
1691     ResultSet rs = null;
1692 
1693     try {
1694       con = ServiceLocator.instance().getConnection();
1695       ps = con.prepareStatement(
1696         "update users set " +
1697         "user_current_sign_on_attempts = 0, " +
1698         "user_date_last_logon = sysdate " +
1699         "where user_id = ?"
1700         );
1701       ps.setLong(1, userId.longValue());
1702 
1703       int n = ps.executeUpdate();
1704 
1705       if(n != 1) {
1706         throw new InstantbankException("131041", "Failed to modify the session information of the user");
1707       }
1708     }
1709     catch(Exception e) {
1710       setRollbackOnly();
1711       throw new InstantbankException(e, "131042", "Failed to modify the session information of the user");
1712     }
1713     finally {
1714       try {
1715         if(ps != null) {
1716           ps.close();
1717         }
1718         if(con != null) {
1719           con.close();
1720         }
1721       }
1722       catch(SQLException se) {
1723       }
1724     }
1725   }
1726 
1727 
1728   public void updateUserGroupLastChanged(Long loggedUser, Long userGroupId) throws InstantbankException {
1729     Connection con = null;
1730     PreparedStatement ps = null;
1731     ResultSet rs = null;
1732 
1733     try {
1734       con = ServiceLocator.instance().getConnection();
1735       ps = con.prepareStatement(
1736         "update user_groups set " +
1737         "usg_last_changed_by = ?, " +
1738         "usg_last_changed_date = sysdate " +
1739         "where usg_id = ?"
1740         );
1741       ps.setLong(1, loggedUser.longValue());
1742       ps.setLong(2, userGroupId.longValue());
1743 
1744       int n = ps.executeUpdate();
1745 
1746       if(n != 1) {
1747         throw new InstantbankException("131029", "Failed to modify the last changed information of the user");
1748       }
1749     }
1750     catch(Exception e) {
1751       setRollbackOnly();
1752       throw new InstantbankException(e, "131030", "Failed to modify the last changed information of the user");
1753     }
1754     finally {
1755       try {
1756         if(ps != null) {
1757           ps.close();
1758         }
1759         if(con != null) {
1760           con.close();
1761         }
1762       }
1763       catch(SQLException se) {
1764       }
1765     }
1766   }
1767 
1768 
1769   public void updateUserLastChanged(Long loggedUser, Long userId) throws InstantbankException {
1770     Connection con = null;
1771     PreparedStatement ps = null;
1772     ResultSet rs = null;
1773 
1774     try {
1775       con = ServiceLocator.instance().getConnection();
1776       ps = con.prepareStatement(
1777         "update users set " +
1778         "user_last_changed_by = ?, " +
1779         "user_last_changed_date = sysdate " +
1780         "where user_id = ?"
1781         );
1782       ps.setLong(1, loggedUser.longValue());
1783       ps.setLong(2, userId.longValue());
1784 
1785       int n = ps.executeUpdate();
1786 
1787       if(n != 1) {
1788         throw new InstantbankException("131031", "Failed to modify the last changed information of the user");
1789       }
1790     }
1791     catch(Exception e) {
1792       setRollbackOnly();
1793       throw new InstantbankException(e, "131032", "Failed to modify the last changed information of the user");
1794     }
1795     finally {
1796       try {
1797         if(ps != null) {
1798           ps.close();
1799         }
1800         if(con != null) {
1801           con.close();
1802         }
1803       }
1804       catch(SQLException se) {
1805       }
1806     }
1807   }
1808 
1809 
1810   public String updateUserPassword(Long userId, String newPassword, Long companyId) throws InstantbankException {
1811     Connection con = null;
1812     String oldPassword = "";
1813     PreparedStatement ps = null;
1814     ResultSet rs = null;
1815     ResultSet rs2 = null;
1816     Statement st = null;
1817     String sql;
1818     String message = "Your password has been changed successfully!!";
1819     int uniquePasswords = 0;
1820     try {
1821 
1822       con = ServiceLocator.instance().getConnection();
1823       st = con.createStatement();
1824 
1825       sql = "SELECT USER_PASSWORD ";
1826       sql += "FROM USERS ";
1827       sql += "WHERE USER_ID = " + userId;
1828 
1829       rs = st.executeQuery(sql);
1830 
1831       if(rs.next()) {
1832         oldPassword = rs.getString(1);
1833       }
1834       rs.close();
1835       sql = "SELECT  CMP_NUMBER_OF_UNIQUE_PASSWORDS ";
1836       sql += "FROM COMPANIES ";
1837       sql += "WHERE CMP_ID = " + companyId;
1838 
1839       rs = st.executeQuery(sql);
1840 
1841       if(rs.next()) {
1842         uniquePasswords = rs.getInt(1);
1843       }
1844       uniquePasswords = uniquePasswords - 1;
1845       sql = " SELECT oldpassword FROM(" +
1846         " SELECT UPP_PASSWORD oldpassword" +
1847         " FROM PREVIOUS_PASSWORDS" +
1848         " WHERE UPP_USER_ID= " + userId +
1849         " ORDER BY UPP_DATE DESC)" +
1850         " WHERE ROWNUM <=" + uniquePasswords;
1851 
1852       rs2 = st.executeQuery(sql);
1853 
1854       while(rs2.next()) {
1855         if(rs2.getString(1).equals(newPassword) || oldPassword.equals(newPassword)) {
1856           return "Your password was not changed- passwords may not be reused until " + (uniquePasswords + 1) + " password changes have ocurred.";
1857         }
1858       }
1859 
1860       long uppId = UniqueIDGenerator.instance().getNextId();
1861       createPreviousPwd(uppId, userId.longValue());
1862       ps = con.prepareStatement("update users set user_password = ?, user_date_pwd_created = sysdate, USER_STATUS_FLAG = 1 where user_id = ? ");
1863       ps.setString(1, newPassword);
1864 
1865       ps.setLong(2, userId.longValue());
1866       int n = ps.executeUpdate();
1867       if(n != 1) {
1868         throw new InstantbankException("131031", "Failed to modify user password");
1869       }
1870 
1871     }
1872     catch(Exception e) {
1873       setRollbackOnly();
1874       throw new InstantbankException(e, "131032", "Failed to modify user password");
1875     }
1876     finally {
1877       try {
1878         if(ps != null) {
1879           ps.close();
1880         }
1881         if(rs2 != null) {
1882           rs2.close();
1883         }
1884         if(rs != null) {
1885           rs.close();
1886         }
1887         if(st != null) {
1888           st.close();
1889         }
1890         if(con != null) {
1891           con.close();
1892         }
1893       }
1894       catch(SQLException se) {
1895       }
1896     }
1897     return message;
1898   }
1899 }
1900