KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > calipso > reportgenerator > usermanager > UserManager


1 package com.calipso.reportgenerator.usermanager;
2 import com.calipso.reportgenerator.common.InfoException;
3
4 import java.util.*;
5 import java.io.IOException JavaDoc;
6
7 import com.calipso.reportgenerator.common.*;
8 import com.calipso.reportgenerator.reportmanager.RolsRepository;
9 import com.calipso.reportgenerator.reportmanager.RolDataRepository;
10 import com.calipso.reportgenerator.reportmanager.UserDataRepository;
11 import com.calipso.reportgenerator.reportmanager.UsersRepository;
12
13  /**
14   *
15   * User: alozada
16   * Date: 08/09/2005
17   * Time: 12:32:29
18   *
19   */

20 public class UserManager {
21    public Map mapObjects = new HashMap();
22    public Map map = new HashMap();
23    public Set listUsers = new TreeSet();
24    public List listRols = new ArrayList();
25    private Collection listeners;
26    private ReportGeneratorConfiguration reportGeneratorConfiguration;
27
28   /**
29    * Crea una instancia de <code>UserManager</code>
30    * @param reportGeneratorConfiguration
31    * @throws InfoException
32    */

33 public UserManager(ReportGeneratorConfiguration reportGeneratorConfiguration) throws InfoException {
34    this.reportGeneratorConfiguration = reportGeneratorConfiguration;
35    this.refreshListUsers();
36    this.refreshListRols();
37    this.refreshMap();
38    this.fillMapToMapRolsRepository();
39     }
40  /**
41   * Utilizado para agregar a un usuario un rol y tambien para agregarle a un rol un usuario.
42   * Verificando que los mismos sean validos para luego almacenarlo primeramente en un mapa,
43   * luego si siguiera la ejecucion correctamente, se volcarian los datos en el file rolsrepository.
44   * @param role
45   * @param us
46   * @throws InfoException
47   */

48 public void addUsersToCollectionRol(Rol role,User us) throws InfoException {
49    if (!(this.isValid(us))){
50       throw new InfoException(LanguageTraslator.traslate("453"));
51       }
52    if (!(this.isValid(role))){
53       throw new InfoException(LanguageTraslator.traslate("454"));
54       }
55   addUserRol( us.getId(),role.getId(),reportGeneratorConfiguration.getRolsRepositoryPath());
56   fireModelChange();
57   }
58  /**
59   * Llama al metodo addUserRol de RolsRepository desde el UserManager, para agragarle al file
60   * rolsRepository el par : "username=rol", lo que quedara actualizado en un mapa (rol->"username", ...,""), para manipularlo
61   * internamente
62   * @param rol
63   * @param rolsRepositoryPath
64   * @throws InfoException
65   */

66
67 private void addUserRol(String JavaDoc userName, String JavaDoc rol, String JavaDoc rolsRepositoryPath) throws InfoException {
68   RolsRepository repository = new RolsRepository(rolsRepositoryPath);
69   repository.addUserRol(userName, rol);
70   refreshMap();
71   fireModelChange();
72   }
73  /**
74   * Devuelve una coleccion con todos los objetos usuario, que existen
75   * @return lista de objetos usuario
76   * @throws InfoException
77   */

78 public Set getUsers() throws InfoException {
79    this.refreshListUsers();
80    return listUsers;
81    }
82
83  /**
84   * Llama al metodo addRol de RolDataRepository desde el UserManager, para agregarle al file
85   * RolData la linea "rol.getId();rol.getDescription()" por ejemplo "rol1;rol1" lo que quedara actualizado
86   * en una coleccion de objetos Roles debiendo por esta actualizacion llamar al fireModelChange que avisara
87   * sobre los cambios
88   * @param rol
89   * @throws InfoException
90   */

91 public void addRol(Rol rol) throws InfoException {
92   RolDataRepository rolsDataRepository;
93   rolsDataRepository = new RolDataRepository(reportGeneratorConfiguration.getRolDataRepositoryPath());
94   rolsDataRepository.addNewRol(rol.getId(),rol.getDescription());
95   listRols.add(rol);
96   fireModelChange();
97   }
98  /**
99   * Llama al metodo addUser de UserDataRepository desde el UserManager, para agregarle al file
100   * UserData la linea "us.getId();us.getUserName();us.getCompany()" por ejemplo "11;Usuario1;Company1" lo que
101   * quedara actualizado en una coleccion de objetos Usuario debiendo por esta actualizacion llamar al
102   * fireModelChange que avisara sobre los cambios
103   *
104   * @param us
105   * @throws InfoException
106   */

107 public void addUser(User us) throws InfoException {
108   UserDataRepository userDataRepository;
109   userDataRepository = new UserDataRepository(reportGeneratorConfiguration.getUserDataRepositoryPath());
110   userDataRepository.addNewUser(us.getId(),us.getUserName(),us.getCompany());
111   listUsers.add(us);
112   fireModelChange();
113   }
114  /**
115   * Obtiene una copia local del mapa que contiene por ejemplo : "rol1-> us1, us2, ..., usn"
116   * con todos los elementos como String.
117   * @throws InfoException
118   */

119
120 private void refreshMap() throws InfoException {
121    RolsRepository repository = new RolsRepository(reportGeneratorConfiguration.getRolsRepositoryPath());
122    map = repository.getMap();
123    fillMapToMapRolsRepository();
124    }
125  /**
126   * Devuelve una lista de objetos Roles , pertenecientes al usuario indicado
127   * como parametro
128   * @param us
129   * @return lista de roles
130   * @throws InfoException
131   */

132 public List getRolsByUser(User us) throws InfoException {
133   fillMapToMapRolsRepository();
134   Iterator it = getMap().entrySet().iterator();
135   List list = new ArrayList();
136   while (it.hasNext()) {
137      Map.Entry e =(Map.Entry) it.next();
138      Rol role = (Rol)e.getKey();
139      List listUsers =(List) e.getValue();
140      if( listUsers.contains(us)) {
141         list.add(role);
142         }
143      }
144   return list;
145   }
146  /**
147   *Devuelve una lista de objetos Usuario , pertenecientes al Rol indicado
148   * como parametro
149   * @param role
150   * @return lista de usuarios
151   * @throws InfoException
152   */

153 public List getUsersByRol(Rol role) throws InfoException {
154    fillMapToMapRolsRepository();
155    List list = new ArrayList();
156    Set keySet = (Set)getMap().keySet();
157    if( keySet.contains(role) ) {
158       list = (List)getMap().get(role);
159    }
160  return list;
161  }
162    /**
163    * Indica si un rol es valido , dentro de la lista de roles
164    * @param role
165    * @return boolean
166    * @throws InfoException
167    */

168     private boolean isValid(Rol role) throws InfoException {
169       this.refreshListRols();
170       return listRols.contains(role);
171    }
172    /**
173    * Indica si un usuario es valido , dentro de la lista de usuarios
174    * @param us
175    * @return boolean
176    * @throws InfoException
177    */

178     private boolean isValid(User us) throws InfoException {
179        this.refreshListUsers();
180        return listUsers.contains(us);
181  }
182
183    /**
184    * Devuelve una lista con todos los objetos usuario q tienen algun rol establecido
185    * (no usado por el momento )
186    * @throws InfoException
187    * @return lista de usuarios
188    */

189     public List getUsersWithRols()throws InfoException {
190        this.refreshMap();
191        this.refreshListUsers();
192        this.fillMapToMapRolsRepository();
193        List list = new ArrayList();
194        Iterator it = getMap().entrySet().iterator();
195        while (it.hasNext()) {
196          Map.Entry e =(Map.Entry) it.next();
197          List list2= (List) e.getValue();
198          Iterator it2 = list2.iterator();
199          while (it2.hasNext()) {
200             User us = (User) it2.next();
201            if(!(list.contains(us))){
202               list.add(us);
203            }
204          }
205       }
206    return list;
207    }
208   /**
209    * Actualiza la lista de usuarios , introduciendo todos los usuarios en una coleccion de objetos usuario
210    * @throws InfoException
211    */

212    private void refreshListUsers() throws InfoException {
213      UserDataRepository userDataRepository = new UserDataRepository(reportGeneratorConfiguration.getUserDataRepositoryPath());
214      listUsers = userDataRepository.getAllUsers();
215    }
216
217    /**
218    * Actualiza la lista de roles , introduciendo todos los roles en una coleccion de objetos rol
219    * @throws InfoException
220    */

221
222    public void refreshListRols()throws InfoException{
223      RolDataRepository rolsDataRepository = new RolDataRepository(reportGeneratorConfiguration.getRolDataRepositoryPath());
224      listRols = (List) rolsDataRepository.getAllRols();
225    }
226
227    /**
228    * Devuelve una coleccion con todos los objetos Roles que existen
229    * @return lista de roles
230    */

231
232    public List getRols() throws InfoException {
233      this.refreshListRols();
234      return listRols;
235    }
236    /**
237    * Recibe un obj usuario, lo valida y luego busca su homólogo al cual reemplazará
238    * @param us
239    * @throws com.calipso.reportgenerator.common.InfoException
240    * @throws IOException
241     */

242    public void modifyUser(User us) throws InfoException, IOException JavaDoc {
243        if (!(this.isValidUserId(us.getId()))){
244          throw new InfoException(LanguageTraslator.traslate("455"));
245       }
246       Iterator it = listUsers.iterator();
247       while (it.hasNext()) {
248          User us1 = (User)it.next();
249           if (us1.getId().equals(us.getId())){
250              UserDataRepository userDataRepository = new UserDataRepository(reportGeneratorConfiguration.getUserDataRepositoryPath());
251              userDataRepository.removeUser(us.getId());
252              this.addUser(us);
253              this.fillMapToMapRolsRepository();
254              break;
255             }
256         }
257     fireModelChange();
258   }
259   /**
260    * Comprueba que el id de usuario pertenezca a alguno de los usuarios, q existen dentro del
261    * entorno
262    * @param idUser
263    * @return boolean
264    */

265      private boolean isValidUserId(String JavaDoc idUser){
266       Iterator it = listUsers.iterator();
267       while (it.hasNext()) {
268          User us = (User)it.next();
269          if (us.getId().equals(idUser)){
270          return true;
271        }
272     }
273     return false;
274     }
275    /**
276    * Comprueba que el id de rol pertenezca a alguno de los roles, q existen dentro del
277    * entorno
278    * @param idRol
279    * @return boolean
280    */

281    private boolean isValidRolId(String JavaDoc idRol){
282      Iterator it = listRols.iterator();
283      while (it.hasNext()) {
284         Rol role = (Rol)it.next();
285         if (role.getId().equals(idRol)){
286           return true;
287         }
288     }
289   return false;
290   }
291
292   /**
293   * Borra un usuario del file de usuarios (UserData) y si el mismo tiene ademas roles , tambien los elimina de
294   * el file de usuarios - roles (rolsRepository), actulizando entre medio los mapas y listas relacionadas
295   * @param us
296   * @return boolean
297   * @throws com.calipso.reportgenerator.common.InfoException
298   * @throws IOException
299   */

300   public boolean removeUser(User us) throws InfoException, IOException JavaDoc {
301     if (!(this.isValid(us))){
302         throw new InfoException(LanguageTraslator.traslate("453"));
303         }
304     UserDataRepository userDataRepository = new UserDataRepository(reportGeneratorConfiguration.getUserDataRepositoryPath());
305     userDataRepository.removeUser(us.getId());
306     refreshListUsers();
307       if (!(hasRol(us))) {
308           return false;
309     }
310     RolsRepository rolsRepository = new RolsRepository(reportGeneratorConfiguration.getRolsRepositoryPath());
311     rolsRepository.removeUser(us.getId());
312     refreshMap();
313     fireModelChange();
314     return true;
315   }
316   /**
317    * Indica si ese usuario tiene ó no rol/es asignados (es decir si existe en el file rolsrepository,
318    * la linea "us1=rol1" por ejemplo, siendo us.id igual a "us1" y rol1 el id de algun rol)
319    * @param us
320    * @return boolean
321    */

322    private boolean hasRol(User us){
323      Iterator it = map.entrySet().iterator();
324      while (it.hasNext()) {
325       Map.Entry e =(Map.Entry) it.next();
326       Vector vector = (Vector)e.getValue();
327        if (vector.contains(us.getId()))
328            return true;
329
330      }
331      return false;
332    }
333   /**
334    * Borra un rol del file de roles (RolData) y si el mismo tiene ademas usuarios , tambien los elimina de
335    * el file de usuarios - roles (rolsRepository), actulizando entre medio los mapas y listas relacionadas
336    * @param role
337    * @return
338    * @throws InfoException
339    * @throws IOException
340    */

341
342    public boolean removeRol(Rol role) throws InfoException, IOException JavaDoc {
343       if (!(this.isValid(role))){
344         throw new InfoException(LanguageTraslator.traslate("454"));
345         }
346     RolDataRepository rolsDataRepository = new RolDataRepository(reportGeneratorConfiguration.getRolDataRepositoryPath());
347     rolsDataRepository.removeRol(role.getId());
348     refreshListRols();
349
350
351     if (!(map.containsKey(role.getId()))) {
352           return false;
353     }
354     RolsRepository rolsRepository = new RolsRepository(reportGeneratorConfiguration.getRolsRepositoryPath());
355     rolsRepository.removeRol(role.getId());
356     refreshMap();
357     fireModelChange();
358     return true;
359   }
360   /**
361    * Avisa al userManagerChange que ha habido una modificacion
362    * en alguno de los metodos
363    */

364
365  private void fireModelChange() {
366       for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
367         UserManagerListener userManagerListener = (UserManagerListener) iterator.next();
368         userManagerListener.userManagerChange(this);
369       }
370     }
371    /**
372     * Agrega a la lista de Listener un nuevo elemento
373     * @param userManagerListener
374     */

375   public void addListener(UserManagerListener userManagerListener) {
376      getListeners().add(userManagerListener);
377    }
378    /**
379     * Devuelve una coleccion con todos los listener que existen por el momento
380     * @return
381     */

382   private Collection getListeners() {
383      if(listeners==null){
384        listeners = new Vector();
385      }
386      return listeners;
387    }
388   /**
389    * Carga un mapa de objetos usuarios / roles(por ejemplo : RoL1-> Us1, Us2 - Rol2-> Us3,Us1 )
390    * partiendo de otro map pero de String (por ejemplo : "rol1" ->"us2" , "us2" - "rol2"-> "us3", "us1")
391    * con las mismas caracateristicas
392    * @throws com.calipso.reportgenerator.common.InfoException
393    */

394   public void fillMapToMapRolsRepository() throws InfoException {
395     map = new HashMap();
396     mapObjects = new HashMap();
397     RolsRepository repository = new RolsRepository(reportGeneratorConfiguration.getRolsRepositoryPath());
398     map = repository.getMap();
399     Iterator it = map.entrySet().iterator();
400
401     while (it.hasNext()) {
402       Map.Entry e =(Map.Entry) it.next();
403       String JavaDoc idRol = (String JavaDoc)e.getKey();
404
405       if (!(isValidRolId(idRol))) {
406         throw new InfoException(LanguageTraslator.traslate("457"));
407       }
408       Rol role = getObjectRolFrom(idRol);
409       Vector vector = (Vector)e.getValue();
410       List users = new ArrayList();
411       for (int i = 0; i < vector.size(); i++) {
412           String JavaDoc idUser = (String JavaDoc)vector.get(i);
413           if (!(isValidUserId(idUser))) {
414             throw new InfoException(LanguageTraslator.traslate("457"));
415           }
416           User us = getObjectUserFrom(idUser);
417           users.add(us);
418         }
419       mapObjects.put(role,users);
420     }
421   }
422      /**
423       * Obtiene a partir de un id del rol, un objeto Rol al q ese identificador corresponde
424       * @param idRol
425       * @return Objeto Rol
426       */

427   private Rol getObjectRolFrom(String JavaDoc idRol){
428     Iterator it = listRols.iterator();
429     while (it.hasNext()) {
430       Rol role = (Rol)it.next();
431       if (role.getId().equals(idRol)){
432          return role;
433           }
434       }
435     return null;
436   }
437      /**
438       * Obtiene apartir de un id de usuario ,un objeto Usuario al q ese identificador corresponde
439       * @param idUser
440       * @return Objeto Usuario
441       */

442    private User getObjectUserFrom(String JavaDoc idUser){
443     Iterator it = listUsers.iterator();
444     while (it.hasNext()) {
445       User us = (User)it.next();
446       if (us.getId().equals(idUser)){
447          return us;
448           }
449       }
450     return null;
451   }
452   /**
453    * Getter del mapa de objetos (por ejemplo : RoL1-> Us1, Us2 - Rol2-> Us3,Us1 )
454    * @return
455    */

456   public Map getMap(){
457      return mapObjects;
458    }
459    /**
460     * Corrobora que el password y el usuario pasados como parametro sean correspondidos
461     * @param userName
462     * @param password
463     * @return boolean
464     * @throws InfoException
465     */

466    public boolean validate(String JavaDoc userName, String JavaDoc password) throws InfoException {
467      UsersRepository usersRepository = new UsersRepository(reportGeneratorConfiguration.getUsersRepositoryPath());
468      return usersRepository.validate(userName,password);
469    }
470     /**
471      * Elimina una relacion entre un usuario y un rol (por ejemplo : " us1=rol1" ),
472      * actualizando el file rolsRepository además de las estructuras concernientes
473      * @param role
474      * @param us
475      * @throws InfoException
476      */

477    public void removeRolToUser(Rol role, User us) throws InfoException{
478        refreshMap();
479        List list;
480        if (!(this.isValid(role))){
481         throw new InfoException(LanguageTraslator.traslate("454"));
482         }
483        if (!(this.isValid(us))){
484         throw new InfoException(LanguageTraslator.traslate("453"));
485         }
486        list =((List)getMap().get(role));
487        if (!(list.remove(us))){
488         throw new InfoException(LanguageTraslator.traslate("456"));
489        }
490       RolsRepository rolsRepository = new RolsRepository(reportGeneratorConfiguration.getRolsRepositoryPath());
491       rolsRepository.removeUser(us.getId());
492       refreshMap();
493       fireModelChange();
494     }
495
496   }
497
498
499
Popular Tags