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