790dbfa550126bbd4a0512a8770cb11b644ca7a4
[vid.git] / vid-app-common / src / main / java / org / onap / vid / services / RoleGenaratorServiceImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2018 - 2019 Nokia. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.vid.services;
23
24 import io.joshworks.restclient.http.HttpResponse;
25 import jline.internal.Log;
26 import org.onap.vid.aai.*;
27 import org.onap.vid.model.ModelConstants;
28 import org.onap.vid.model.Subscriber;
29 import org.onap.vid.model.SubscriberList;
30 import org.springframework.beans.factory.annotation.Autowired;
31 import org.springframework.stereotype.Service;
32
33 import java.util.HashMap;
34
35 @Service
36 public class RoleGenaratorServiceImpl implements RoleGeneratorService {
37
38     public static final String ROLE_ID_COLUMN = "ROLE_ID";
39
40     @Autowired
41     AaiClientInterface client;
42
43     @Autowired
44     AaiOverTLSClientInterface aaiOverTLSClient;
45
46     public static final String DB_NAME =  "vid_portal";
47     public static final String TBL_NAME = "fn_role";
48     public static final String TEMP_DELIMITER ="***";
49     public static final String OLD_DELIMITER = "_";
50
51     @Override
52     public String generateRoleScript(Boolean firstRun) {
53         String query =  "USE " + DB_NAME + ";\r\n" +
54                 "SET SQL_SAFE_UPDATES = 0;\r\n";
55         try {
56             HttpResponse<SubscriberList> allSubscribers = aaiOverTLSClient.getAllSubscribers();
57             if (firstRun) {
58                 query += replaceRolesToTempDelimiter("subscriber",buildSubscribersValuesForMappingsTable(allSubscribers.getBody()));
59             }
60             query += addAvailableRolesCombination(firstRun, allSubscribers.getBody());
61
62         }
63         catch (Exception e) {
64             Log.error("There was an error in updating roles ", e);
65         }
66         return query;
67     }
68
69     private String addAvailableRolesCombination(Boolean firstRun, SubscriberList subscribers) {
70         String query;
71         String availableRoles="";
72         HashMap<String,String> servicesNames = new HashMap<>();
73         for (Subscriber subscriber: subscribers.customer) {
74             AaiResponse<Services> subscriberResponse = client.getSubscriberData(subscriber.globalCustomerId);
75             for(ServiceSubscription service: subscriberResponse.getT().serviceSubscriptions.serviceSubscription) {
76                 servicesNames.put(service.serviceType,"");
77                 String roleName = "'" + subscriber.subscriberName + ModelConstants.ROLE_DELIMITER + service.serviceType + "'";
78                 availableRoles += "("+roleName+"),";
79
80
81             }
82         }
83         availableRoles = availableRoles.substring(0,availableRoles.length()-1);
84         query = createTemporaryTableAvailableRoles(availableRoles);
85         if (firstRun){
86             query += replaceRolesToTempDelimiter("service",buildServicesValuesForMappingsTable(servicesNames));
87             query += replaceToNewDelimiter();
88             query += deleteWrongRecords();
89
90         }
91         query += insertAvailableRolesToFnRole();
92         query += dropTemporaryTable("available_roles");
93         return query;
94     }
95
96     private String buildSubscribersValuesForMappingsTable(SubscriberList subscribers){
97         String query="";
98         for (Subscriber subscriber : subscribers.customer) {
99             String subscriberName = subscriber.subscriberName.contains(OLD_DELIMITER) ? subscriber.subscriberName.replace(OLD_DELIMITER, TEMP_DELIMITER) : subscriber.subscriberName;
100             query = query + "('" + subscriber.globalCustomerId + "','" + subscriberName + "') ,";
101         }
102         if(query.length() > 0)
103             query = query.substring(0, query.length()-1) + ";\r\n";
104         return query;
105     }
106
107     private String buildServicesValuesForMappingsTable(HashMap<String,String> servicesNames){
108         final String[] query = {""};
109         servicesNames.forEach((k,v)->{
110             if (k.contains(OLD_DELIMITER)) {
111                 query[0] += "('" + k + "' ,'" + k.replace(OLD_DELIMITER, TEMP_DELIMITER) +"'),";
112             }
113         });
114         if(query[0].length() > 0)
115             query[0] = query[0].substring(0, query[0].length()-1) + ";\r\n";
116         return query[0];
117     }
118
119     private String replaceRolesToTempDelimiter(String entityName, String valuesForMappingsTable ) {
120
121         AaiResponse<Services> services = client.getServices();
122         String query = "";
123         if (valuesForMappingsTable.length() > 0) {
124             query = "CREATE TEMPORARY TABLE IF NOT EXISTS " + entityName + "Mappings(mapKey VARCHAR(255),mapValue VARCHAR(255));\r\n" +
125                     "INSERT INTO " + entityName + "Mappings VALUES ";
126             query += valuesForMappingsTable;
127             query += "UPDATE " + TBL_NAME + "\r\n" +
128                     "INNER JOIN " + entityName + "Mappings ON role_name LIKE concat('%',mapKey, '%')\r\n" +
129                     "SET ROLE_NAME = REPLACE(ROLE_NAME, mapKey, mapValue) ;  \r\n" +
130                     dropTemporaryTable(entityName + "Mappings");
131         }
132         return query;
133     }
134
135     private String replaceToNewDelimiter(){
136         String query =  "UPDATE " + TBL_NAME + "\r\n" +
137                 "SET ROLE_NAME = REPLACE(ROLE_NAME, '" + OLD_DELIMITER + "', '" + ModelConstants.ROLE_DELIMITER + "');\r\n" ;
138         query += "UPDATE fn_role\r\n" +
139                 "SET ROLE_NAME = REPLACE(ROLE_NAME, '" + TEMP_DELIMITER + "', '" + OLD_DELIMITER + "');\r\n" ;
140         return query;
141     }
142
143     private String insertAvailableRolesToFnRole(){
144          return "INSERT INTO fn_role (ROLE_NAME, ACTIVE_YN, PRIORITY)\r\n" +
145                 "SELECT RNAME, 'Y', 5\r\n" +
146                 "FROM available_roles\r\n" +
147                 "WHERE NOT EXISTS (SELECT ROLE_NAME\r\n" +
148                 "FROM fn_role \r\n" +
149                 "where RNAME = ROLE_NAME);\r\n";
150     }
151
152
153
154     private String createTemporaryTableAvailableRoles(String availableRoles) {
155         String query = "CREATE TEMPORARY TABLE IF NOT EXISTS available_roles(rname VARCHAR(255));\r\n";
156         query += "INSERT INTO available_roles VALUES "+availableRoles+";\r\n";
157                 return query;
158     }
159
160     private String deleteWrongRecords(){
161         String query ="CREATE TEMPORARY TABLE IF NOT EXISTS wrong_roles(roleID INT);\r\n" +
162                 "INSERT INTO wrong_roles (roleID)\r\n" +
163                 "SELECT ROLE_ID FROM fn_role LEFT JOIN available_roles ON role_name LIKE concat(rname, '%')\r\n" +
164                 "WHERE available_roles.rname IS NULL AND ROLE_ID NOT IN (1,16);\r\n";
165         query += deleteCascade();
166         query += dropTemporaryTable("wrong_roles");
167         return query;
168     }
169
170     private String deleteCascade() {
171         String query = deleteFromTableByRoles("fn_role_composite", "PARENT_ROLE_ID");
172         query = query.substring(0, query.length()-1);
173         query += " OR wrong_roles.ROLEID = fn_role_composite.CHILD_ROLE_ID;\r\n";
174         query += deleteFromTableByRoles("fn_role_function", ROLE_ID_COLUMN)+ "\r\n";
175         query += deleteFromTableByRoles("fn_user_role", ROLE_ID_COLUMN)+ "\r\n";
176         query += deleteFromTableByRoles(TBL_NAME, ROLE_ID_COLUMN)+ "\r\n";
177         return query;
178     }
179
180     private String deleteFromTableByRoles(String table, String column) {
181         String query = "DELETE FROM " + table + "\r\n";
182         query += "using  " + table + " inner join wrong_roles\r\n" +
183                 "where wrong_roles.ROLEID = " + table + "." + column + ";";
184         return query;
185     }
186
187     private String dropTemporaryTable(String table) {
188         return "DROP TEMPORARY TABLE IF EXISTS " + table + ";\r\n";
189     }
190 }