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