Initial code Import.
[music.git] / src / main / java / org / onap / music / main / CachingUtil.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  * ===================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  * 
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  * 
19  * ============LICENSE_END=============================================
20  * ====================================================================
21  */
22 package org.onap.music.main;
23
24 import java.util.Arrays;
25 import java.util.Calendar;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.Map;
29 import java.util.UUID;
30 import javax.ws.rs.core.HttpHeaders;
31 import javax.ws.rs.core.MediaType;
32 import org.apache.commons.codec.binary.Base64;
33 import org.apache.commons.jcs.JCS;
34 import org.apache.commons.jcs.access.CacheAccess;
35 import org.apache.log4j.Logger;
36 import org.codehaus.jackson.map.ObjectMapper;
37 import org.onap.music.datastore.jsonobjects.AAFResponse;
38 import com.att.eelf.configuration.EELFLogger;
39 import com.att.eelf.configuration.EELFManager;
40 import org.onap.music.datastore.PreparedQueryObject;
41 import com.datastax.driver.core.DataType;
42 import com.datastax.driver.core.ResultSet;
43 import com.datastax.driver.core.Row;
44 import com.sun.jersey.api.client.Client;
45 import com.sun.jersey.api.client.ClientResponse;
46 import com.sun.jersey.api.client.WebResource;
47
48 /**
49  * All Caching related logic is handled by this class and a schedule cron runs to update cache.
50  * 
51  * @author Vikram
52  *
53  */
54 public class CachingUtil implements Runnable {
55
56     private static EELFLogger logger = EELFManager.getInstance().getLogger(CachingUtil.class);
57
58     private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
59     private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
60     private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
61     private static Map<String, Number> userAttempts = new HashMap<>();
62     private static Map<String, Calendar> lastFailedTime = new HashMap<>();
63
64     public boolean isCacheRefreshNeeded() {
65         if (aafCache.get("initBlankMap") == null)
66             return true;
67         return false;
68     }
69
70     public void initializeMusicCache() {
71         logger.info("Initializing Music Cache...");
72         musicCache.put("isInitialized", "true");
73     }
74
75     public void initializeAafCache() {
76         logger.info("Resetting and initializing AAF Cache...");
77
78         // aafCache.clear();
79         // loop through aafCache ns .. only the authenticated ns will be re cached. and non
80         // authenticated will wait for user to retry.
81         String query = "SELECT application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
82         PreparedQueryObject pQuery = new PreparedQueryObject();
83         pQuery.appendQueryString(query);
84         try {
85             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
86         } catch (Exception e1) {
87             e1.printStackTrace();
88             logger.error("Exception is " + e1.getMessage() + "during initalizeAafCache");
89         }
90         ResultSet rs = MusicCore.get(pQuery);
91         Iterator<Row> it = rs.iterator();
92         Map<String, String> map = null;
93         while (it.hasNext()) {
94             Row row = it.next();
95             String nameSpace = row.getString("keyspace_name");
96             String userId = row.getString("username");
97             String password = row.getString("password");
98             String keySpace = row.getString("application_name");
99             try {
100                 userAttempts.put(nameSpace, 0);
101                 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
102                 if (responseObj.getNs().size() > 0) {
103                     map = new HashMap<>();
104                     map.put(userId, password);
105                     aafCache.put(nameSpace, map);
106                     musicCache.put(nameSpace, keySpace);
107                     logger.debug("Cronjob: Cache Updated with AAF response for namespace "
108                                     + nameSpace);
109                 }
110             } catch (Exception e) {
111                 // TODO Auto-generated catch block
112                 e.printStackTrace();
113                 logger.error("Something at AAF was changed for ns: " + nameSpace
114                                 + ". So not updating Cache for the namespace. ");
115                 logger.error("Exception is " + e.getMessage());
116             }
117         }
118
119     }
120
121     @Override
122     public void run() {
123         logger.debug("Scheduled task invoked. Refreshing Cache...");
124         initializeAafCache();
125     }
126
127     public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
128                     String keySpace) throws Exception {
129
130         if (aafCache.get(nameSpace) != null) {
131             if (!musicCache.get(nameSpace).equals(keySpace)) {
132                 logger.debug("Create new application for the same namespace.");
133             } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
134                 logger.debug("Authenticated with cache value..");
135                 // reset invalid attempts to 0
136                 userAttempts.put(nameSpace, 0);
137                 return true;
138             } else {
139                 // call AAF update cache with new password
140                 if (userAttempts.get(nameSpace) == null)
141                     userAttempts.put(nameSpace, 0);
142                 if ((Integer) userAttempts.get(nameSpace) >= 3) {
143                     logger.info("Reached max attempts. Checking if time out..");
144                     logger.info("Failed time: " + lastFailedTime.get(nameSpace).getTime());
145                     Calendar calendar = Calendar.getInstance();
146                     long delayTime = (calendar.getTimeInMillis()
147                                     - lastFailedTime.get(nameSpace).getTimeInMillis());
148                     logger.info("Delayed time: " + delayTime);
149                     if (delayTime > 120000) {
150                         logger.info("Resetting failed attempt.");
151                         userAttempts.put(nameSpace, 0);
152                     } else {
153                         throw new Exception(
154                                         "No more attempts allowed. Please wait for atleast 2 min.");
155                     }
156                 }
157                 logger.error("Cache not authenticated..");
158                 logger.info("Check AAF again...");
159             }
160         }
161
162         AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
163         if (responseObj.getNs().size() > 0) {
164             if (responseObj.getNs().get(0).getAdmin().contains(userId))
165                 return true;
166
167         }
168         logger.info("Invalid user. Cache not updated");
169         return false;
170     }
171
172     private static AAFResponse triggerAAF(String nameSpace, String userId, String password)
173                     throws Exception {
174         if (MusicUtil.getAafEndpointUrl() == null) {
175             throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
176         }
177         Client client = Client.create();
178         // WebResource webResource =
179         // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
180         WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
181         String plainCreds = userId + ":" + password;
182         byte[] plainCredsBytes = plainCreds.getBytes();
183         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
184         String base64Creds = new String(base64CredsBytes);
185
186         ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
187                         .header("Authorization", "Basic " + base64Creds)
188                         .header("content-type", "application/json").get(ClientResponse.class);
189         if (response.getStatus() != 200) {
190             if (userAttempts.get(nameSpace) == null)
191                 userAttempts.put(nameSpace, 0);
192             if ((Integer) userAttempts.get(nameSpace) >= 2) {
193                 lastFailedTime.put(nameSpace, Calendar.getInstance());
194                 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
195                 throw new Exception(
196                                 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
197             }
198             userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
199             throw new Exception(
200                             "Unable to authenticate. Please check the AAF credentials against namespace.");
201             // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
202             // for specific time.
203         }
204         response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
205                         Arrays.asList(MediaType.APPLICATION_JSON));
206         // AAFResponse output = response.getEntity(AAFResponse.class);
207         response.bufferEntity();
208         String x = response.getEntity(String.class);
209         AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);
210         return responseObj;
211     }
212
213     public static Map<String, Object> authenticateAIDUser(String aid, String keyspace)
214                     throws Exception {
215         Map<String, Object> resultMap = new HashMap<>();
216         String uuid = null;
217         /*
218          * if(aid == null || aid.length() == 0) { resultMap.put("Exception Message",
219          * "AID is missing for the keyspace requested."); //create a new AID ?? } else
220          */
221         if (musicCache.get(keyspace) == null) {
222             PreparedQueryObject pQuery = new PreparedQueryObject();
223             pQuery.appendQueryString(
224                             "SELECT uuid from admin.keyspace_master where keyspace_name = '"
225                                             + keyspace + "' allow filtering");
226             Row rs = MusicCore.get(pQuery).one();
227             try {
228                 uuid = rs.getUUID("uuid").toString();
229                 musicCache.put(keyspace, uuid);
230             } catch (Exception e) {
231                 String msg = e.getMessage();
232                 logger.error("Exception occured during uuid retrieval from DB." + e.getMessage());
233                 resultMap.put("Exception", "Unauthorized operation. Check AID and Keyspace. "
234                                 + "Exception from MUSIC is: "
235                                 + (msg == null ? "Keyspace is new so no AID should be passed in Header."
236                                                 : msg));
237                 return resultMap;
238             }
239             if (!musicCache.get(keyspace).toString().equals(aid)) {
240                 resultMap.put("Exception Message",
241                                 "Unauthorized operation. Invalid AID for the keyspace");
242                 return resultMap;
243             }
244         } else if (musicCache.get(keyspace) != null
245                         && !musicCache.get(keyspace).toString().equals(aid)) {
246             resultMap.put("Exception Message",
247                             "Unauthorized operation. Invalid AID for the keyspace");
248             return resultMap;
249         }
250         resultMap.put("aid", uuid);
251         return resultMap;
252     }
253
254     public static void updateMusicCache(String aid, String keyspace) {
255         logger.info("Updating musicCache for keyspace " + keyspace + " with aid " + aid);
256         musicCache.put(keyspace, aid);
257     }
258
259     public static void updateisAAFCache(String namespace, String isAAF) {
260         appNameCache.put(namespace, isAAF);
261     }
262
263     public static Boolean isAAFApplication(String namespace) {
264
265         String isAAF = appNameCache.get(namespace);
266         if (isAAF == null) {
267             PreparedQueryObject pQuery = new PreparedQueryObject();
268             pQuery.appendQueryString(
269                             "SELECT is_aaf from admin.keyspace_master where application_name = '"
270                                             + namespace + "' allow filtering");
271             Row rs = MusicCore.get(pQuery).one();
272             try {
273                 isAAF = String.valueOf(rs.getBool("is_aaf"));
274                 appNameCache.put(namespace, isAAF);
275             } catch (Exception e) {
276                 logger.error("Exception occured during uuid retrieval from DB." + e.getMessage());
277                 e.printStackTrace();
278             }
279         }
280         return Boolean.valueOf(isAAF);
281     }
282
283     public static String getUuidFromMusicCache(String keyspace) {
284         String uuid = musicCache.get(keyspace);
285         if (uuid == null) {
286             PreparedQueryObject pQuery = new PreparedQueryObject();
287             pQuery.appendQueryString(
288                             "SELECT uuid from admin.keyspace_master where keyspace_name = '"
289                                             + keyspace + "' allow filtering");
290             Row rs = MusicCore.get(pQuery).one();
291             try {
292                 uuid = rs.getUUID("uuid").toString();
293                 musicCache.put(keyspace, uuid);
294             } catch (Exception e) {
295                 logger.error("Exception occured during uuid retrieval from DB." + e.getMessage());
296                 e.printStackTrace();
297             }
298         }
299         return uuid;
300     }
301
302     public static String getAppName(String keyspace) {
303         String appName = null;
304         PreparedQueryObject pQuery = new PreparedQueryObject();
305         pQuery.appendQueryString(
306                         "SELECT application_name from admin.keyspace_master where keyspace_name = '"
307                                         + keyspace + "' allow filtering");
308         Row rs = MusicCore.get(pQuery).one();
309         try {
310             appName = rs.getString("application_name");
311         } catch (Exception e) {
312             logger.error("Exception occured during uuid retrieval from DB." + e.getMessage());
313             e.printStackTrace();
314         }
315         return appName;
316     }
317
318     public static String generateUUID() {
319         String uuid = UUID.randomUUID().toString();
320         logger.info("New AID generated: " + uuid);
321         return uuid;
322     }
323
324     public static Map<String, Object> validateRequest(String nameSpace, String userId,
325                     String password, String keyspace, String aid, String operation) {
326         Map<String, Object> resultMap = new HashMap<>();
327         if (!"createKeySpace".equals(operation)) {
328             if (nameSpace == null) {
329                 resultMap.put("Exception", "Application namespace is mandatory.");
330             }
331         }
332         return resultMap;
333
334     }
335
336     public static Map<String, Object> verifyOnboarding(String ns, String userId, String password)
337                     throws Exception {
338         Map<String, Object> resultMap = new HashMap<>();
339         if (ns == null || userId == null || password == null) {
340             logger.error("One or more required headers is missing. userId: " + userId
341                             + " :: password: " + password);
342             resultMap.put("Exception",
343                             "One or more required headers appName(ns), userId, password is missing. Please check.");
344             return resultMap;
345         }
346         PreparedQueryObject queryObject = new PreparedQueryObject();
347         queryObject.appendQueryString(
348                         "select * from admin.keyspace_master where application_name=? and username=? allow filtering");
349         queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
350         queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
351         Row rs = MusicCore.get(queryObject).one();
352         if (rs == null) {
353             logger.error("Namespace and UserId doesn't match. namespace: " + ns + " and userId: "
354                             + userId);
355             resultMap.put("Exception", "Application " + ns
356                             + " doesn't seem to be Onboarded. Please onboard your application with MUSIC. If already onboarded contact Admin");
357         } else {
358             boolean is_aaf = rs.getBool("is_aaf");
359             String keyspace = rs.getString("keyspace_name");
360             if (!is_aaf) {
361                 if (!keyspace.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
362                     logger.error("Non AAF applications are allowed to have only one keyspace per application.");
363                     resultMap.put("Exception",
364                                     "Non AAF applications are allowed to have only one keyspace per application.");
365                 }
366             }
367         }
368         return resultMap;
369     }
370 }