Salome HOME
Fixes for checkin and user creation.
[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         protected final static Logger LOG = 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(final User.Properties uprop)
68                         throws MissedPropertyException, InvalidPropertyException,
69                         MultiplyDefinedException, RuntimeException {
70                 User nuser = new User(uprop);
71                 // Do merge to synchronize Role object with the current hibernate session
72                 // and to avoid th exception:
73                 // org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the
74                 // session: [org.splat.dal.bo.kernel.Role#simer]
75                 getUserDAO().merge(nuser);
76                 
77                 getUserDAO().create(nuser);
78                 return nuser;
79         }
80
81         // For the casting List<String>
82         @Transactional
83         public Set<User> importUsers(final File xfile) throws XMLException,
84                         MismatchException {
85                 String[] name = xfile.getName().split("\\x2E"); // Split by '.' (period) character
86                 String fext = name[name.length - 1];
87
88                 if (!fext.equals("xml")) {
89                         throw new MismatchException("filetype");
90                 }
91                 try {
92                         DocumentBuilderFactory dfactory = javax.xml.parsers.DocumentBuilderFactory
93                                         .newInstance();
94                         DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
95                         org.w3c.dom.Document inDoc = dBuilder.parse(xfile);
96                         String xtag = inDoc.getDocumentElement().getNodeName();
97                         if (!xtag.equals("users")) {
98                                 throw new MismatchException("filetype");
99                         }
100                         org.w3c.dom.NodeList ulist = inDoc.getElementsByTagName("user");
101
102                         // List<String> result = (List<String>) session
103                         // .createSQLQuery("SELECT * FROM users")
104                         // .addScalar("username").list();
105                         List<User> users = getUserDAO().getAll();
106                         HashSet<String> members = new HashSet<String>();
107                         HashSet<User> imported = new HashSet<User>();
108                         for (Iterator<User> i = users.iterator(); i.hasNext();) {
109                                 members.add(i.next().getUsername());
110                         }
111
112                         for (int i = 0; i < ulist.getLength(); i++) {
113                                 HashMap<String, Node> row = XDOM.getNamedChildNodes(ulist
114                                                 .item(i));
115                                 User.Properties uprop = new User.Properties();
116
117                                 // Mandatory properties
118                                 String uname = row.get("username").getTextContent();
119                                 if (members.contains(uname)) {
120                                         continue; // This user already exists
121                                 }
122                                 uprop.setUsername(uname).setFirstName(
123                                                 row.get("first").getTextContent()).setName(
124                                                 row.get("last").getTextContent()).setMailAddress(
125                                                 row.get("mail").getTextContent()).addRole(
126                                                 row.get("role").getTextContent()); // Add all roles at a time
127
128                                 // Optional properties
129                                 org.w3c.dom.Node node = row.get("password");
130                                 if (node != null) {
131                                         uprop.setPassword(node.getTextContent());
132                                 }
133                                 node = row.get("display");
134                                 if (node != null) {
135                                         uprop.setDisplayName(node.getTextContent());
136                                 }
137                                 node = row.get("organization");
138                                 if (node != null) {
139                                         uprop.setOrganizationName(node.getTextContent());
140                                 }
141                                 // Addition of the user
142                                 uprop.disableCheck(); // Existent user already checked above
143                                 User newser = new User(uprop);
144                                 getUserDAO().create(newser);
145                                 imported.add(newser);
146                         }
147                         return imported;
148                 } catch (IOException error) {
149                         LOG.debug(error.getMessage(), error);
150                         throw new XMLException("XML users file not found"); // RKV: NOPMD: Original message is printed
151                 } catch (ParserConfigurationException e) {
152                         LOG.debug(e.getMessage(), e);
153                         throw new XMLException("XML Organization parser not accessible"); // RKV: NOPMD: Original message is printed
154                 } catch (Exception e) {
155                         LOG.debug(e.getMessage(), e);
156                         throw new XMLException("XML users file not valid"); // RKV: NOPMD: Original message is printed
157                 }
158         }
159
160         /**
161          * Returns the manager of the given user. This function is effective providing that users are defined according to the following
162          * conventions:
163          * <ul>
164          * <li>One user is assigned in the organization as Nx1 (n+1 manager of members of the organization)</li>
165          * <li>Another user is assigned in the organization as Nx2 (n+2 manager of members of the organization)</li>
166          * </ul>
167          * If such users do not exit, null is returned.
168          * 
169          * @param user
170          *            the user whose manager is get
171          * @return the manager of the given user, if defined
172          */
173         public User getManagerOf(final User user) {
174                 User result = null;
175                 String orgname = user.getOrganizationName();
176
177                 if (orgname.equals("Nx2")) {
178                         return result;
179                 }
180                 if (orgname.equals("Nx1")) {
181                         orgname = "Nx2";
182                 } else {
183                         if (user.getRoleNames().equals("customer")) {
184                                 return result;
185                         }
186                         orgname = "Nx1";
187                 }
188                 try {
189                         User.Properties uprop = new User.Properties();
190                         List<User> ulist = selectUsersWhere(uprop
191                                         .setOrganizationName(orgname));
192                         return ulist.get(0); // n+1 and n+2 managers are unique
193                 } catch (Exception e) {
194                         return null;
195                 }
196         }
197
198         @Transactional(readOnly = true)
199         public List<User> selectAllUsers() {
200                 // String query = "FROM User order by last asc, first asc";
201                 return getUserDAO().getAll(Order.asc("last"), Order.asc("first"));
202         }
203
204         @Transactional(readOnly = true)
205         public User selectUser(final String username) {
206                 return getUserDAO().findByCriteria(
207                                 Restrictions.eq("username", username));
208         }
209
210         public User selectUser(final String username, final String password) {
211                 // WARNING: For not encoding the password here, we better call a selectUsersWhere(User.Properties),
212                 // but this requires a getPassword in User.Properties nested class.
213                 Criterion aCondition = Restrictions.eq("username", username);
214                 if (password == null) {
215                         aCondition = Restrictions.and(aCondition, Restrictions
216                                         .isNull("password"));
217                 } else {
218                         aCondition = Restrictions.and(aCondition, Restrictions.eq(
219                                         "password", String.valueOf(password.hashCode())));
220                 }
221                 return getUserDAO().findByCriteria(aCondition);
222         }
223
224         @Transactional(readOnly = true)
225         public User selectUser(final long index) {
226                 return getUserDAO().get(index);
227         }
228
229         @SuppressWarnings("unchecked")
230         public List<User> selectUsersWhere(final User.Properties... uprop) {
231                 // StringBuffer query = new StringBuffer("FROM User");
232                 // String separator = " where (";
233                 // String value;
234                 //
235                 // for (int i = 0; i < uprop.length; i++) {
236                 //
237                 // value = uprop[i].getOrganizationName();
238                 // if (value != null) {
239                 // query = query.append(separator).append(" organid='")
240                 // .append(value).append("'");
241                 // // separator = " and";
242                 // }
243                 // separator = ") or (";
244                 // }
245                 // query.append(")");
246                 Criterion aCondition = null;
247                 String value;
248                 for (int i = 0; i < uprop.length; i++) {
249                         value = uprop[i].getOrganizationName();
250                         if (value != null) {
251                                 if (aCondition == null) {
252                                         aCondition = Restrictions.eq("organid", value);
253                                 } else {
254                                         aCondition = Restrictions.or(aCondition, Restrictions.eq(
255                                                         "organid", value));
256                                 }
257                         }
258                 }
259                 return getUserDAO().getFilteredList(aCondition);
260         }
261
262         /**
263          * Get the userDAO.
264          * 
265          * @return the userDAO
266          */
267         public UserDAO getUserDAO() {
268                 return _userDAO;
269         }
270
271         /**
272          * Set the userDAO.
273          * 
274          * @param userDAO
275          *            the userDAO to set
276          */
277         public void setUserDAO(final UserDAO userDAO) {
278                 _userDAO = userDAO;
279         }
280 }