1 package org.splat.kernel;
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/>
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).
14 * @author Daniel Brunier-Coulin
15 * @copyright OPEN CASCADE 2012
18 import java.io.IOException;
20 import java.util.HashSet;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.List;
26 import javax.xml.parsers.DocumentBuilder;
27 import javax.xml.parsers.DocumentBuilderFactory;
28 import javax.xml.parsers.ParserConfigurationException;
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;
39 public class UserDirectory {
41 final static Logger logger = Logger.getLogger(UserDirectory.class);
43 // ==============================================================================================================================
45 // ==============================================================================================================================
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();
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();
63 if (!fext.equals("xml")) throw new MismatchException("filetype");
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");
72 List<String> result = (List<String>)session.createSQLQuery("SELECT * FROM users").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());
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();
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
90 // Optional properties
91 org.w3c.dom.Node node = row.get("password");
93 uprop.setPassword(node.getTextContent());
95 node = row.get("display");
97 uprop.setDisplayName(node.getTextContent());
99 node = row.get("organization");
101 uprop.setOrganizationName(node.getTextContent());
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);
111 catch (IOException error) {
112 throw new XMLException("XML users file not found");
114 catch (ParserConfigurationException e) {
115 throw new XMLException("XML Organization parser not accessible");
117 catch (Exception e) {
118 throw new XMLException("XML users file not valid");
123 * Returns the manager of the given user.
124 * This function is effective providing that users are defined according to the following conventions:
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>
129 * If such users do not exit, null is returned.
131 * @param user the user whose manager is get
132 * @return the manager of the given user, if defined
134 public static User getManagerOf (User user) {
135 // -------------------------------------------
137 String orgname = user.getOrganizationName();
139 if (orgname.equals("Nx2")) return result;
140 if (orgname.equals("Nx1")) orgname = "Nx2";
142 if (user.getRoleNames().equals("customer")) return result;
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
150 catch (Exception e) {
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();
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();
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("'");
176 return (User)Database.getSession().createQuery(query.toString()).uniqueResult();
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();
185 @SuppressWarnings("unchecked")
186 public static List<User> selectUsersWhere (User.Properties... uprop) {
187 // --------------------------------------------------------------------
188 StringBuffer query = new StringBuffer("FROM User");
189 String separator = " where (";
192 for (int i=0; i<uprop.length; i++) {
194 value = uprop[i].getOrganizationName();
196 query = query.append(separator).append(" organid='").append(value).append("'");
197 // separator = " and";
199 separator = ") or (";
202 return (List<User>)Database.getSession().createQuery(query.toString()).list();