Salome HOME
Siman codebase is refactored. Spring beans are introduced in the context.
[tools/siman.git] / Workspace / Siman-Common / src / org / splat / kernel / UserDirectory.java
1 package org.splat.kernel;
2 /**
3  * Very minimal implementation of the user directory of a company department.<br/>
4  * This directory can include members of the department, the two level hierarchy of these members (their n+1 and n+2 managers),
5  * and all customers of the department.<br/>
6  * The department hierarchy is defined through a hard-coded combination of user role and organization names (see the getManagerOf
7  * function of this class). It is useful for implementing an application workflow requiring such informmation (the n+1 and n+2
8  * managers are usually involved in the validation process).<br/>
9  * <br/>
10  * When needed, a full implementation of the company organization can be adjoin to this class by using user organization names
11  * as reference to departments into this organization. In this context, the function getManagerOf(user) of this class will be
12  * ineffective (it will return null).
13  * 
14  * @author    Daniel Brunier-Coulin
15  * @copyright OPEN CASCADE 2012
16  */
17
18 import java.io.IOException;
19 import java.io.File;
20 import java.util.HashSet;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Set;
25
26 import javax.xml.parsers.DocumentBuilder;
27 import javax.xml.parsers.DocumentBuilderFactory;
28 import javax.xml.parsers.ParserConfigurationException;
29
30 import org.hibernate.Session;
31 import org.splat.dal.bo.kernel.User;
32 import org.splat.dal.dao.som.Database;
33 import org.splat.manox.XDOM;
34 import org.splat.manox.XMLException;
35 import org.w3c.dom.Node;
36 import org.apache.log4j.Logger;
37
38
39 public class UserDirectory {
40         
41     final static Logger logger = Logger.getLogger(UserDirectory.class);
42
43 //  ==============================================================================================================================
44 //  Public services     
45 //  ==============================================================================================================================
46
47         public static User createUser (User.Properties uprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException, RuntimeException {
48 //  -----------------------------------------------------
49           User    nuser   = new User(uprop);
50       Session session = Database.getSession();
51       session.save(nuser);
52         
53       return nuser;
54         }
55
56     @SuppressWarnings("unchecked")                            // For the casting List<String>
57         public static Set<User> importUsers (File xfile) throws XMLException, MismatchException, RuntimeException {
58 //  ------------------------------------------------
59           String[] name    = xfile.getName().split("\\x2E");   // Split by '.' (period) character
60           String   fext    = name[name.length-1];
61       Session  session = Database.getSession();
62       
63           if (!fext.equals("xml")) throw new MismatchException("filetype");
64           try {
65                 DocumentBuilderFactory dfactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
66                 DocumentBuilder        dBuilder = dfactory.newDocumentBuilder();                                        
67                 org.w3c.dom.Document   inDoc    = dBuilder.parse(xfile);
68                 String                 xtag     = inDoc.getDocumentElement().getNodeName();
69         if (!xtag.equals("users")) throw new MismatchException("filetype");
70                 org.w3c.dom.NodeList   ulist    = inDoc.getElementsByTagName("user");
71         
72         List<String>    result   = (List<String>)session.createSQLQuery("SELECT * FROM user").addScalar("username").list();
73         HashSet<String> members  = new HashSet<String>();
74         HashSet<User>   imported = new HashSet<User>();
75         for (Iterator<String> i=result.iterator(); i.hasNext();) members.add(i.next());
76         
77                 for (int i=0; i<ulist.getLength(); i++) {
78                   HashMap<String, Node> row   = XDOM.getNamedChildNodes(ulist.item(i));
79                   User.Properties       uprop = new User.Properties();
80
81 //        Mandatory properties
82                   String uname  = row.get("username").getTextContent();
83                   if (members.contains(uname)) continue;            // This user already exists
84                   uprop.setUsername(uname)
85                        .setFirstName(row.get("first").getTextContent())
86                        .setName(row.get("last").getTextContent())
87                        .setMailAddress(row.get("mail").getTextContent())
88                        .addRole(row.get("role").getTextContent());  // Add all roles at a time
89
90 //        Optional properties
91                   org.w3c.dom.Node node = row.get("password");
92                   if (node != null) {
93                         uprop.setPassword(node.getTextContent());
94                   }
95                   node = row.get("display");
96                   if (node != null) {
97                         uprop.setDisplayName(node.getTextContent());
98                   }
99                   node = row.get("organization");
100                   if (node != null) {
101                         uprop.setOrganizationName(node.getTextContent());
102                   }
103 //        Addition of the user
104                   uprop.disableCheck();                             // Existent user already checked above
105           User         newser = new User(uprop);
106                   session.save(newser);
107                   imported.add(newser);
108                 }
109                 return  imported;
110           }
111       catch (IOException error) {
112         throw new XMLException("XML users file not found");
113       }
114           catch (ParserConfigurationException e) {
115                 throw new XMLException("XML Organization parser not accessible");
116           }
117           catch (Exception e) {
118                 throw new XMLException("XML users file not valid");
119           }
120     }
121
122 /**
123  * Returns the manager of the given user.
124  * This function is effective providing that users are defined according to the following conventions:
125  * <ul>
126  * <li>One user is assigned in the organization as Nx1 (n+1 manager of members of the organization)</li>
127  * <li>Another user is assigned in the organization as Nx2 (n+2 manager of members of the organization)</li>
128  * </ul>
129  * If such users do not exit, null is returned.
130  * 
131  * @param user the user whose manager is get
132  * @return the manager of the given user, if defined
133  */
134     public static User getManagerOf (User user) {
135 //  -------------------------------------------
136       User   result  = null;
137       String orgname = user.getOrganizationName();
138
139       if (orgname.equals("Nx2"))                    return result;
140       if (orgname.equals("Nx1")) orgname = "Nx2";
141       else {
142         if (user.getRoleNames().equals("customer")) return result;
143         orgname = "Nx1";
144       }
145       try {
146         User.Properties uprop = new User.Properties();
147         List<User>      ulist = UserDirectory.selectUsersWhere(uprop.setOrganizationName(orgname));
148         return ulist.get(0);     // n+1 and n+2 managers are unique
149       }
150       catch (Exception e) {
151         return null;
152       }
153     }
154
155         @SuppressWarnings("unchecked")                            // For the casting List<User>
156         public static List<User> selectAllUsers () {
157 //  ------------------------------------------
158           String query = "from User order by last asc, first asc";
159           return (List<User>)Database.getSession().createQuery(query).list();
160         }
161
162         public static User selectUser (String username) {
163 //  -----------------------------------------------
164           StringBuffer  query = new StringBuffer("from User where username='").append(username).append("'");
165           return (User)Database.getSession().createQuery(query.toString()).uniqueResult();
166         }
167
168         public static User selectUser (String username, String password) {
169 //  ----------------------------------------------------------------
170 //WARNING: For not encoding the password here, we better call a selectUsersWhere(User.Properties),
171 //         but this requires a getPassword in User.Properties nested class.
172           StringBuffer  query = new StringBuffer("from User where username='").append(username).append("' and password");
173           if (password == null) query = query.append(" is null");
174           else                  query = query.append("='").append(String.valueOf(password.hashCode())).append("'");
175           
176           return (User)Database.getSession().createQuery(query.toString()).uniqueResult();
177         }
178
179     public static User selectUser (int index) {
180 //  -----------------------------------------
181       StringBuffer  query = new StringBuffer("from User where rid='").append(index).append("'");
182       return (User)Database.getSession().createQuery(query.toString()).uniqueResult();
183         }
184
185     @SuppressWarnings("unchecked")
186         public static List<User> selectUsersWhere (User.Properties... uprop) {
187 //  --------------------------------------------------------------------
188       StringBuffer query     = new StringBuffer("from User");
189       String       separator = " where (";
190       String       value;
191
192       for (int i=0; i<uprop.length; i++) {
193
194         value = uprop[i].getOrganizationName();
195         if (value != null) {
196           query     = query.append(separator).append(" organid='").append(value).append("'");
197 //        separator = " and";
198         }
199         separator = ") or (";
200       }
201       query.append(")");
202       return (List<User>)Database.getSession().createQuery(query.toString()).list();
203     }
204 }