282be90675c89f4c28cec3b944ef1562c5b85d2c
[vid.git] / vid-automation / src / main / java / vid / automation / test / services / UsersService.java
1 package vid.automation.test.services;
2
3 import com.att.automation.common.report_portal_integration.annotations.Step;
4 import com.google.common.primitives.Ints;
5 import org.apache.commons.lang3.StringUtils;
6 import vid.automation.test.model.User;
7 import vid.automation.test.model.UsersObject;
8 import vid.automation.test.utils.DB_CONFIG;
9 import vid.automation.test.utils.ReadFile;
10
11 import java.sql.Connection;
12 import java.sql.DriverManager;
13 import java.sql.SQLException;
14 import java.sql.Statement;
15 import java.util.HashMap;
16 import java.util.LinkedList;
17 import java.util.List;
18 import java.util.ListIterator;
19
20 import static org.hamcrest.CoreMatchers.everyItem;
21 import static org.hamcrest.MatcherAssert.assertThat;
22 import static org.hamcrest.Matchers.greaterThan;
23
24 /**
25  * Created by itzikliderman on 08/09/2017.
26  */
27 public class UsersService {
28     private HashMap<String, User> users;
29
30     public UsersService() {
31         users = getUsersFromJson();
32         users.forEach(this::prepareUser);
33     }
34
35     HashMap<String, User> getUsersFromJson() {
36         UsersObject usersObject = null;
37         usersObject = ReadFile.getJsonFile("users", UsersObject.class);
38         return usersObject.users;
39     }
40
41     @Step("${method} with id: ${userId}")
42     public User getUser(String userId) {
43         User res = users.get(userId);
44         System.out.println("getUser userId='" + userId + "' returned: " + res);
45
46         if (res == null) {
47             throw new RuntimeException("user id '" + userId + "' is not defined (these ARE defined: " + users.keySet() + ")");
48         }
49
50         return res;
51     }
52
53
54     private void prepareUser(String userId, User user) {
55         /*
56         Creates a user in the DB, were:
57          -  Login user name is a deterministic number, hashed from the userId string, with 3 trailing zeroes,
58             and two leading letters from the userId itself; e.g. "mo26063000" for mobility.
59          -  Login user name == user password
60          -  'user.credentials.userId' and 'user.credentials.password' input fields are overridden with the generated values.
61          -  Roles are "read" (roleId==16) and all other roles in object (like subscriberName___serviceType___tenant).
62          -  Yielded role ids are the successive numbers after the user name. e.g "57174000", "57174001", "57174002".
63          */
64
65         dropUser(userId);
66
67         System.out.println("Preparing user '" + userId + "': " + user);
68         System.out.println("Connecting database...");
69
70         try (Connection connection = DriverManager.getConnection(DB_CONFIG.url, DB_CONFIG.username, DB_CONFIG.password)) {
71
72             System.out.println("Database connected!");
73
74             ///////////////////////////////
75             // Add user with specific roles
76             Statement stmt = connection.createStatement();
77             int userNumber = getUserNumber(userId);
78             user.credentials.userId = getLoginId(userId);
79             user.credentials.password = getLoginId(userId);
80
81             stmt.addBatch("INSERT INTO `fn_user` (`USER_ID`, `ORG_USER_ID`, `FIRST_NAME`, `LOGIN_ID`, `LOGIN_PWD`) " +
82                     "VALUES (" + userNumber + ", '" + userId + "', '" + userId + "', '" + user.credentials.userId + "', '" + user.credentials.password + "')");
83
84             List<String> roles = user.roles != null ? user.roles : new LinkedList<>();
85             roles.add("Standard User");
86
87             ListIterator<String> iter = roles.listIterator();
88             while (iter.hasNext()) {
89                 int roleNumber = userNumber + iter.nextIndex();
90
91                 String sql = "INSERT INTO `fn_role` (`ROLE_ID`, `ROLE_NAME`, `ACTIVE_YN`, `PRIORITY`) VALUES (" + roleNumber + ", '" + iter.next() + "', 'Y', " + 5 + ")";
92                 System.out.println(sql);
93                 stmt.addBatch(sql);
94                 String sql2 = "INSERT INTO `fn_user_role` (`USER_ID`, `ROLE_ID`, `PRIORITY`, `APP_ID`) VALUES (" + userNumber + ", " + roleNumber + ", NULL, 1)";
95                 System.out.println(sql2);
96                 stmt.addBatch(sql2);
97             }
98             stmt.addBatch("INSERT INTO `fn_user_role` (`USER_ID`, `ROLE_ID`, `PRIORITY`, `APP_ID`) VALUES (" + userNumber + ", 16, NULL, 1)");
99
100             int[] executeBatch = stmt.executeBatch();
101             assertThat(Ints.asList(executeBatch), everyItem(greaterThan(0)));
102
103         } catch (SQLException e) {
104             throw new IllegalStateException("Cannot connect the database!", e);
105         }
106
107     }
108
109     private void dropUser(String userId) {
110         System.out.println("Dropping user '" + userId + "'");
111         System.out.println("Connecting database...");
112
113         try (Connection connection = DriverManager.getConnection(DB_CONFIG.url, DB_CONFIG.username, DB_CONFIG.password)) {
114
115             System.out.println("Database connected!");
116
117             int userNumber = getUserNumber(userId);
118             Statement stmt = connection.createStatement();
119             stmt.addBatch("DELETE FROM `fn_user_role` WHERE `USER_ID` = " + userNumber);
120             stmt.addBatch("DELETE FROM `fn_role` WHERE `ROLE_ID` BETWEEN " + userNumber + " AND " + (userNumber + 100));
121             stmt.addBatch("DELETE FROM `fn_user` WHERE `USER_ID` = " + userNumber);
122             int[] executeBatch = stmt.executeBatch();
123
124         } catch (SQLException e) {
125             throw new IllegalStateException("Cannot connect the database!", e);
126         }
127     }
128
129     private int getUserNumber(String userId) {
130         return (Math.abs(userId.hashCode()) % 100000) * 1000;
131     }
132
133     private String getLoginId(String userId) {
134         int userNumber = getUserNumber(userId);
135         final String twoCharacters = StringUtils.substring(userId,0, 2).toLowerCase();
136         return String.format("%s%d", twoCharacters, userNumber);
137     }
138
139 }