View Javadoc

1   /**
2    * 
3    */
4   package sf.net.kayestry.workbench;
5   
6   import javax.servlet.ServletContextEvent;
7   
8   import org.apache.commons.logging.Log;
9   import org.apache.commons.logging.LogFactory;
10  
11  import ar.com.jiji.kaya.KayaRuntimeException;
12  import ar.com.jiji.kaya.RoleNotFoundException;
13  import ar.com.jiji.kaya.dao.RoleDao;
14  import ar.com.jiji.kaya.dao.UserDao;
15  import ar.com.jiji.kaya.model.Role;
16  import ar.com.jiji.kaya.model.User;
17  import ar.com.jiji.kaya.utils.UserUtils;
18  
19  /**
20   * @author lparra
21   * 
22   */
23  public class WebAppInit extends ar.com.jiji.kaya.app.WebAppInit {
24  
25  	private final static Log log = LogFactory.getLog(WebAppInit.class);
26  
27  	@Override
28  	public void contextInitialized(ServletContextEvent event) {
29  		super.contextInitialized(event);
30  		try {
31  			initUsers();
32  		} catch (RoleNotFoundException e) {
33  			// no tendria que pasar
34  			throw new KayaRuntimeException(e);
35  		}
36  		initDireccion();
37  	}
38  
39  	private void initDireccion() {
40  		
41  	}
42  
43  	private void initUsers() throws RoleNotFoundException {
44  		log.debug("init users");
45  
46  		ProjectServiceImpl service = Application.getProjectService();
47  		RoleDao roleDao = service.getRoleDao();
48  		addRoles(roleDao, "demo", "demo2");
49  		addUsers(service.getUserDao(), roleDao, "123456", "demo", "demo2");
50  	}
51  
52  	/**
53  	 * Crea usuarios con los nombres especificados. El rol asignado es el mismo
54  	 * con el nombre del usuario.
55  	 * 
56  	 * @param userDao
57  	 * @param roleDao
58  	 * @param usernames
59  	 * @throws RoleNotFoundException
60  	 */
61  	private void addUsers(UserDao userDao, RoleDao roleDao, String password,
62  			String... usernames) throws RoleNotFoundException {
63  		// FIXME: agregar otro find en el dao, que busque por nombre.
64  		for (String username : usernames)
65  			if (userDao.findByCredentials(username, password) == null) {
66  				UserUtils utils = new UserUtils(roleDao);
67  				User user = new User(username, password);
68  				// uso el mismo nombre de usuario como rol
69  				utils.initializeUser(user, username);
70  				userDao.save(user);
71  			}
72  	}
73  
74  	/**
75  	 * Crea roles.
76  	 * 
77  	 * @param roleDao
78  	 * @param roles
79  	 */
80  	private void addRoles(RoleDao roleDao, String... roles) {
81  		for (String role : roles)
82  			if (roleDao.findByName(role) == null)
83  				roleDao.save(new Role(role));
84  	}
85  
86  }