]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman-Common/src/org/splat/service/UserServiceImpl.java
Salome HOME
Refactoring continues: UserService is created instead of UserDirectory. Database...
[tools/siman.git] / Workspace / Siman-Common / src / org / splat / service / UserServiceImpl.java
1 /*****************************************************************************
2  * Company         OPEN CASCADE
3  * Application     SIMAN
4  * File            $Id$ 
5  * Creation date   21.10.2012
6  * @author         $Author$
7  * @version        $Revision$
8  * @copyright      OPEN CASCADE 2012
9  *****************************************************************************/
10
11 package org.splat.service;
12
13 import java.io.File;
14 import java.io.IOException;
15 import java.util.HashMap;
16 import java.util.HashSet;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.Set;
20
21 import javax.xml.parsers.DocumentBuilder;
22 import javax.xml.parsers.DocumentBuilderFactory;
23 import javax.xml.parsers.ParserConfigurationException;
24
25 import org.apache.log4j.Logger;
26 import org.hibernate.criterion.Criterion;
27 import org.hibernate.criterion.Order;
28 import org.hibernate.criterion.Restrictions;
29 import org.splat.dal.bo.kernel.User;
30 import org.splat.dal.dao.kernel.UserDAO;
31 import org.splat.kernel.InvalidPropertyException;
32 import org.splat.kernel.MismatchException;
33 import org.splat.kernel.MissedPropertyException;
34 import org.splat.kernel.MultiplyDefinedException;
35 import org.splat.manox.XDOM;
36 import org.splat.manox.XMLException;
37 import org.springframework.transaction.annotation.Transactional;
38 import org.w3c.dom.Node;
39
40 /**
41  * User service implementation.
42  * 
43  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
44  */
45 public class UserServiceImpl implements UserService {
46
47         /**
48          * The service logger.
49          */
50         final static Logger logger = Logger.getLogger(UserServiceImpl.class);
51
52         /**
53          * Injected user DAO.
54          */
55         private UserDAO _userDAO;
56
57         // ==============================================================================================================================
58         // Public services
59         // ==============================================================================================================================
60
61         /**
62          * {@inheritDoc}
63          * 
64          * @see org.splat.service.UserService#createUser(org.splat.dal.bo.kernel.User.Properties)
65          */
66         @Transactional
67         public User createUser(User.Properties uprop)
68                         throws MissedPropertyException, InvalidPropertyException,
69                         MultiplyDefinedException, RuntimeException {
70                 User nuser = new User(uprop);
71                 getUserDAO().create(nuser);
72                 return nuser;
73         }
74
75         // For the casting List<String>
76         @Transactional
77         public Set<User> importUsers(File xfile) throws XMLException,
78                         MismatchException {
79                 String[] name = xfile.getName().split("\\x2E"); // Split by '.' (period) character
80                 String fext = name[name.length - 1];
81
82                 if (!fext.equals("xml"))
83                         throw new MismatchException("filetype");
84                 try {
85                         DocumentBuilderFactory dfactory = javax.xml.parsers.DocumentBuilderFactory
86                                         .newInstance();
87                         DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
88                         org.w3c.dom.Document inDoc = dBuilder.parse(xfile);
89                         String xtag = inDoc.getDocumentElement().getNodeName();
90                         if (!xtag.equals("users"))
91                                 throw new MismatchException("filetype");
92                         org.w3c.dom.NodeList ulist = inDoc.getElementsByTagName("user");
93
94                         // List<String> result = (List<String>) session
95                         // .createSQLQuery("SELECT * FROM users")
96                         // .addScalar("username").list();
97                         List<User> users = getUserDAO().getAll();
98                         HashSet<String> members = new HashSet<String>();
99                         HashSet<User> imported = new HashSet<User>();
100                         for (Iterator<User> i = users.iterator(); i.hasNext();)
101                                 members.add(i.next().getUsername());
102
103                         for (int i = 0; i < ulist.getLength(); i++) {
104                                 HashMap<String, Node> row = XDOM.getNamedChildNodes(ulist
105                                                 .item(i));
106                                 User.Properties uprop = new User.Properties();
107
108                                 // Mandatory properties
109                                 String uname = row.get("username").getTextContent();
110                                 if (members.contains(uname))
111                                         continue; // This user already exists
112                                 uprop.setUsername(uname)
113                                                 .setFirstName(row.get("first").getTextContent())
114                                                 .setName(row.get("last").getTextContent())
115                                                 .setMailAddress(row.get("mail").getTextContent())
116                                                 .addRole(row.get("role").getTextContent()); // Add all roles at a time
117
118                                 // Optional properties
119                                 org.w3c.dom.Node node = row.get("password");
120                                 if (node != null) {
121                                         uprop.setPassword(node.getTextContent());
122                                 }
123                                 node = row.get("display");
124                                 if (node != null) {
125                                         uprop.setDisplayName(node.getTextContent());
126                                 }
127                                 node = row.get("organization");
128                                 if (node != null) {
129                                         uprop.setOrganizationName(node.getTextContent());
130                                 }
131                                 // Addition of the user
132                                 uprop.disableCheck(); // Existent user already checked above
133                                 User newser = new User(uprop);
134                                 getUserDAO().create(newser);
135                                 imported.add(newser);
136                         }
137                         return imported;
138                 } catch (IOException error) {
139                         throw new XMLException("XML users file not found");
140                 } catch (ParserConfigurationException e) {
141                         throw new XMLException("XML Organization parser not accessible");
142                 } catch (Exception e) {
143                         throw new XMLException("XML users file not valid");
144                 }
145         }
146
147         /**
148          * Returns the manager of the given user. This function is effective providing that users are defined according to the following
149          * conventions:
150          * <ul>
151          * <li>One user is assigned in the organization as Nx1 (n+1 manager of members of the organization)</li>
152          * <li>Another user is assigned in the organization as Nx2 (n+2 manager of members of the organization)</li>
153          * </ul>
154          * If such users do not exit, null is returned.
155          * 
156          * @param user
157          *            the user whose manager is get
158          * @return the manager of the given user, if defined
159          */
160         public User getManagerOf(User user) {
161                 User result = null;
162                 String orgname = user.getOrganizationName();
163
164                 if (orgname.equals("Nx2"))
165                         return result;
166                 if (orgname.equals("Nx1"))
167                         orgname = "Nx2";
168                 else {
169                         if (user.getRoleNames().equals("customer"))
170                                 return result;
171                         orgname = "Nx1";
172                 }
173                 try {
174                         User.Properties uprop = new User.Properties();
175                         List<User> ulist = selectUsersWhere(uprop
176                                         .setOrganizationName(orgname));
177                         return ulist.get(0); // n+1 and n+2 managers are unique
178                 } catch (Exception e) {
179                         return null;
180                 }
181         }
182
183         @Transactional(readOnly = true)
184         public List<User> selectAllUsers() {
185                 // String query = "FROM User order by last asc, first asc";
186                 return getUserDAO().getAll(Order.asc("last"), Order.asc("first"));
187         }
188
189         @Transactional(readOnly = true)
190         public User selectUser(String username) {
191                 return getUserDAO().findByCriteria(
192                                 Restrictions.eq("username", username));
193         }
194
195         public User selectUser(String username, String password) {
196                 // WARNING: For not encoding the password here, we better call a selectUsersWhere(User.Properties),
197                 // but this requires a getPassword in User.Properties nested class.
198                 Criterion aCondition = Restrictions.eq("username", username);
199                 if (password == null) {
200                         aCondition = Restrictions.and(aCondition,
201                                         Restrictions.isNull("password"));
202                 } else {
203                         aCondition = Restrictions.and(
204                                         aCondition,
205                                         Restrictions.eq("password",
206                                                         String.valueOf(password.hashCode())));
207                 }
208                 return getUserDAO().findByCriteria(aCondition);
209         }
210
211         @Transactional(readOnly = true)
212         public User selectUser(long index) {
213                 return getUserDAO().get(index);
214         }
215
216         @SuppressWarnings("unchecked")
217         public List<User> selectUsersWhere(User.Properties... uprop) {
218 //              StringBuffer query = new StringBuffer("FROM User");
219 //              String separator = " where (";
220 //              String value;
221 //
222 //              for (int i = 0; i < uprop.length; i++) {
223 //
224 //                      value = uprop[i].getOrganizationName();
225 //                      if (value != null) {
226 //                              query = query.append(separator).append(" organid='")
227 //                                              .append(value).append("'");
228 //                              // separator = " and";
229 //                      }
230 //                      separator = ") or (";
231 //              }
232 //              query.append(")");
233                 Criterion aCondition = null;
234                 String value;
235                 for (int i = 0; i < uprop.length; i++) {
236                         value = uprop[i].getOrganizationName();
237                         if (value != null) {
238                                 if (aCondition == null) {
239                                         aCondition = Restrictions.eq("organid", value);
240                                 } else {
241                                         aCondition = Restrictions.or(aCondition, Restrictions.eq("organid", value));
242                                 }
243                         }
244                 }
245                 return getUserDAO().getFilteredList(aCondition);
246         }
247
248         /**
249          * Get the userDAO.
250          * 
251          * @return the userDAO
252          */
253         public UserDAO getUserDAO() {
254                 return _userDAO;
255         }
256
257         /**
258          * Set the userDAO.
259          * 
260          * @param userDAO
261          *            the userDAO to set
262          */
263         public void setUserDAO(UserDAO userDAO) {
264                 _userDAO = userDAO;
265         }
266 }