500f5ac7fca6dd6e0ee21757f583840b0952997a
[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 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2018 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.AaiClientInterface;
27 import org.onap.vid.aai.AaiOverTLSClientInterface;
28 import org.onap.vid.aai.AaiResponse;
29 import org.onap.vid.aai.ServiceSubscription;
30 import org.onap.vid.aai.Services;
31 import org.onap.vid.model.ModelConstants;
32 import org.onap.vid.model.Subscriber;
33 import org.onap.vid.model.SubscriberList;
34 import org.springframework.beans.factory.annotation.Autowired;
35 import org.springframework.beans.factory.annotation.Qualifier;
36 import org.springframework.stereotype.Service;
37
38 import java.util.HashMap;
39
40 @Service
41 public class RoleGenaratorServiceImpl implements RoleGeneratorService {
42
43     public static final String ROLE_ID_COLUMN = "ROLE_ID";
44
45     @Autowired
46     AaiClientInterface client;
47
48     @Autowired
49     @Qualifier("aaiClientForCodehausMapping")
50     AaiOverTLSClientInterface aaiOverTLSClient;
51
52     public static final String DB_NAME =  "vid_portal";
53     public static final String TBL_NAME = "fn_role";
54     public static final String TEMP_DELIMITER ="***";
55     public static final String OLD_DELIMITER = "_";
56
57     @Override
58     public String generateRoleScript(Boolean firstRun) {
59         String query =  "USE " + DB_NAME + ";\r\n" +
60                 "SET SQL_SAFE_UPDATES = 0;\r\n";
61         try {
62             HttpResponse<SubscriberList> allSubscribers = aaiOverTLSClient.getAllSubscribers();
63             if (firstRun) {
64                 query += replaceRolesToTempDelimiter("subscriber",buildSubscribersValuesForMappingsTable(allSubscribers.getBody()));
65             }
66             query += addAvailableRolesCombination(firstRun, allSubscribers.getBody());
67
68         }
69         catch (Exception e) {
70             Log.error("There was an error in updating roles "+e.getMessage());
71         }
72         return query;
73     }
74
75     private String addAvailableRolesCombination(Boolean firstRun, SubscriberList subscribers) {
76         String query, availableRoles="";
77         HashMap<String,String> servicesNames = new HashMap<String,String>();
78         for (Subscriber subscriber: subscribers.customer) {
79             AaiResponse<Services> subscriberResponse = client.getSubscriberData(subscriber.globalCustomerId);
80             for(ServiceSubscription service: subscriberResponse.getT().serviceSubscriptions.serviceSubscription) {
81                 servicesNames.put(service.serviceType,"");
82                 String roleName = "'" + subscriber.subscriberName + ModelConstants.ROLE_DELIMITER + service.serviceType + "'";
83                 availableRoles += "("+roleName+"),";
84
85
86             }
87         }
88         availableRoles = availableRoles.substring(0,availableRoles.length()-1);
89         query = createTemporaryTableAvailableRoles(availableRoles);
90         if (firstRun){
91             query += replaceRolesToTempDelimiter("service",buildServicesValuesForMappingsTable(servicesNames));
92             query += replaceToNewDelimiter();
93             query += deleteWrongRecords();
94
95         }
96         query += insertAvailableRolesToFnRole();
97         query += dropTemporaryTable("available_roles");
98         return query;
99     }
100
101     private String buildSubscribersValuesForMappingsTable(SubscriberList subscribers){
102         String query="";
103         for (Subscriber subscriber : subscribers.customer) {
104             String subscriberName = subscriber.subscriberName.contains(OLD_DELIMITER) ? subscriber.subscriberName.replace(OLD_DELIMITER, TEMP_DELIMITER) : subscriber.subscriberName;
105             query = query + "('" + subscriber.globalCustomerId + "','" + subscriberName + "') ,";
106         }
107         if(query.length() > 0)
108             query = query.substring(0, query.length()-1) + ";\r\n";
109         return query;
110     }
111
112     private String buildServicesValuesForMappingsTable(HashMap<String,String> servicesNames){
113         final String[] query = {""};
114         servicesNames.forEach((k,v)->{
115             if (k.contains(OLD_DELIMITER)) {
116                 query[0] += "('" + k + "' ,'" + k.replace(OLD_DELIMITER, TEMP_DELIMITER) +"'),";
117             }
118         });
119         if(query[0].length() > 0)
120             query[0] = query[0].substring(0, query[0].length()-1) + ";\r\n";
121         return query[0];
122     }
123
124     private String replaceRolesToTempDelimiter(String entityName, String valuesForMappingsTable ) {
125
126         AaiResponse<Services> services = client.getServices();
127         String query = "";
128         if (valuesForMappingsTable.length() > 0) {
129             query = "CREATE TEMPORARY TABLE IF NOT EXISTS " + entityName + "Mappings(mapKey VARCHAR(255),mapValue VARCHAR(255));\r\n" +
130                     "INSERT INTO " + entityName + "Mappings VALUES ";
131             query += valuesForMappingsTable;
132             query += "UPDATE " + TBL_NAME + "\r\n" +
133                     "INNER JOIN " + entityName + "Mappings ON role_name LIKE concat('%',mapKey, '%')\r\n" +
134                     "SET ROLE_NAME = REPLACE(ROLE_NAME, mapKey, mapValue) ;  \r\n" +
135                     dropTemporaryTable(entityName + "Mappings");
136         }
137         return query;
138     }
139
140     private String replaceToNewDelimiter(){
141         String query =  "UPDATE " + TBL_NAME + "\r\n" +
142                 "SET ROLE_NAME = REPLACE(ROLE_NAME, '" + OLD_DELIMITER + "', '" + ModelConstants.ROLE_DELIMITER + "');\r\n" ;
143         query += "UPDATE fn_role\r\n" +
144                 "SET ROLE_NAME = REPLACE(ROLE_NAME, '" + TEMP_DELIMITER + "', '" + OLD_DELIMITER + "');\r\n" ;
145         return query;
146     }
147
148     private String insertAvailableRolesToFnRole(){
149         String query="INSERT INTO fn_role (ROLE_NAME, ACTIVE_YN, PRIORITY)\r\n" +
150                 "SELECT RNAME, 'Y', 5\r\n" +
151                 "FROM available_roles\r\n" +
152                 "WHERE NOT EXISTS (SELECT ROLE_NAME\r\n" +
153                 "FROM fn_role \r\n" +
154                 "where RNAME = ROLE_NAME);\r\n";
155         return query;
156     }
157
158
159
160     private String createTemporaryTableAvailableRoles(String availableRoles) {
161         String query = "CREATE TEMPORARY TABLE IF NOT EXISTS available_roles(rname VARCHAR(255));\r\n";
162         query += "INSERT INTO available_roles VALUES "+availableRoles+";\r\n";
163                 return query;
164     }
165
166     private String deleteWrongRecords(){
167         String query ="CREATE TEMPORARY TABLE IF NOT EXISTS wrong_roles(roleID INT);\r\n" +
168                 "INSERT INTO wrong_roles (roleID)\r\n" +
169                 "SELECT ROLE_ID FROM fn_role LEFT JOIN available_roles ON role_name LIKE concat(rname, '%')\r\n" +
170                 "WHERE available_roles.rname IS NULL AND ROLE_ID NOT IN (1,16);\r\n";
171         query += deleteCascade();
172         query += dropTemporaryTable("wrong_roles");
173         return query;
174     }
175
176     private String deleteCascade() {
177         String query = deleteFromTableByRoles("fn_role_composite", "PARENT_ROLE_ID");
178         query = query.substring(0, query.length()-1);
179         query += " OR wrong_roles.ROLEID = fn_role_composite.CHILD_ROLE_ID;\r\n";
180         query += deleteFromTableByRoles("fn_role_function", ROLE_ID_COLUMN)+ "\r\n";
181         query += deleteFromTableByRoles("fn_user_role", ROLE_ID_COLUMN)+ "\r\n";
182         query += deleteFromTableByRoles(TBL_NAME, ROLE_ID_COLUMN)+ "\r\n";
183         return query;
184     }
185
186     private String deleteFromTableByRoles(String table, String column) {
187         String query = "DELETE FROM " + table + "\r\n";
188         query += "using  " + table + " inner join wrong_roles\r\n" +
189                 "where wrong_roles.ROLEID = " + table + "." + column + ";";
190         return query;
191     }
192
193     private String dropTemporaryTable(String table) {
194         return "DROP TEMPORARY TABLE IF EXISTS " + table + ";\r\n";
195     }
196 }