Add voting app example
[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.codehaus.jackson.map.ObjectMapper;
36 import org.onap.music.datastore.PreparedQueryObject;
37 import org.onap.music.datastore.jsonobjects.AAFResponse;
38 import org.onap.music.eelf.logging.EELFLoggerDelegate;
39 import org.onap.music.eelf.logging.format.AppMessages;
40 import org.onap.music.eelf.logging.format.ErrorSeverity;
41 import org.onap.music.eelf.logging.format.ErrorTypes;
42 import org.onap.music.exceptions.MusicServiceException;
43
44 import com.att.eelf.configuration.EELFLogger;
45 import com.datastax.driver.core.DataType;
46 import com.datastax.driver.core.ResultSet;
47 import com.datastax.driver.core.Row;
48 import com.datastax.driver.core.exceptions.InvalidQueryException;
49 import com.sun.jersey.api.client.Client;
50 import com.sun.jersey.api.client.ClientResponse;
51 import com.sun.jersey.api.client.WebResource;
52
53 /**
54  * All Caching related logic is handled by this class and a schedule cron runs to update cache.
55  * 
56  * @author Vikram
57  *
58  */
59 public class CachingUtil implements Runnable {
60
61     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
62
63     private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
64     private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
65     private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
66     private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
67     private static Map<String, Number> userAttempts = new HashMap<>();
68     private static Map<String, Calendar> lastFailedTime = new HashMap<>();
69
70     public boolean isCacheRefreshNeeded() {
71         if (aafCache.get("initBlankMap") == null)
72             return true;
73         return false;
74     }
75
76     public void initializeMusicCache() {
77         logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
78         musicCache.put("isInitialized", "true");
79     }
80
81     public void initializeAafCache() throws MusicServiceException {
82         logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
83
84         String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
85         PreparedQueryObject pQuery = new PreparedQueryObject();
86         pQuery.appendQueryString(query);
87         try {
88             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
89         } catch (Exception e1) {
90             logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
91             e1.printStackTrace();
92         }
93         ResultSet rs = MusicCore.get(pQuery);
94         Iterator<Row> it = rs.iterator();
95         Map<String, String> map = null;
96         while (it.hasNext()) {
97             Row row = it.next();
98             String nameSpace = row.getString("keyspace_name");
99             String userId = row.getString("username");
100             String password = row.getString("password");
101             String keySpace = row.getString("application_name");
102             try {
103                 userAttempts.put(nameSpace, 0);
104                 boolean aafRresponse = triggerAAF(nameSpace, userId, password);
105                 if (aafRresponse) {
106                     map = new HashMap<>();
107                     map.put(userId, password);
108                     aafCache.put(nameSpace, map);
109                     musicCache.put(keySpace, nameSpace);
110                     logger.debug("Cronjob: Cache Updated with AAF response for namespace "
111                                     + nameSpace);
112                 }
113             } catch (Exception e) {
114                 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
115                 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
116                 e.printStackTrace();
117             }
118         }
119
120     }
121
122     @Override
123     public void run() {
124         logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
125         try {
126                         initializeAafCache();
127                 } catch (MusicServiceException e) {
128                         logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
129                 }
130     }
131
132     public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
133                     String keySpace) throws Exception {
134
135         if (aafCache.get(nameSpace) != null) {
136           /*  if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) {
137                 logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
138             } else */if (aafCache.get(nameSpace).get(userId).equals(password)) {
139                 logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
140                 // reset invalid attempts to 0
141                 userAttempts.put(nameSpace, 0);
142                 return true;
143             } else {
144                 // call AAF update cache with new password
145                 if (userAttempts.get(nameSpace) == null)
146                     userAttempts.put(nameSpace, 0);
147                 if ((Integer) userAttempts.get(nameSpace) >= 3) {
148                     logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
149                     logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
150                     Calendar calendar = Calendar.getInstance();
151                     long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
152                     logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
153                     if( delayTime > 120000) {
154                         logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
155                         userAttempts.put(nameSpace, 0);
156                     } else {
157                         logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
158                         throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
159                     }
160                 }
161                 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
162                 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
163             }
164         }
165
166         boolean aafRresponse = triggerAAF(nameSpace, userId, password);
167         if (aafRresponse) {
168                 //TODO
169             //if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
170                 Map<String, String> map = new HashMap<>();
171                 map.put(userId, password);
172                 aafCache.put(nameSpace, map);
173                 return true;
174             //}
175         }
176         logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
177         return aafRresponse;
178     }
179
180     private static boolean triggerAAF(String nameSpace, String userId, String password)
181                     throws Exception {
182         if (MusicUtil.getAafEndpointUrl() == null) {
183                 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
184             throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
185         }
186         Client client = Client.create();
187         // WebResource webResource =
188         // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
189         WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
190         String plainCreds = userId + ":" + password;
191         byte[] plainCredsBytes = plainCreds.getBytes();
192         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
193         String base64Creds = new String(base64CredsBytes);
194
195         ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
196                         .header("Authorization", "Basic " + base64Creds)
197                         .header("content-type", "application/json").get(ClientResponse.class);
198         if(response.getStatus() == 200) 
199                 return true;
200         else if (response.getStatus() != 200) {
201             if (userAttempts.get(nameSpace) == null)
202                 userAttempts.put(nameSpace, 0);
203             if ((Integer) userAttempts.get(nameSpace) >= 2) {
204                 lastFailedTime.put(nameSpace, Calendar.getInstance());
205                 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
206                 throw new Exception(
207                                 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
208             }
209             userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
210             throw new Exception(
211                             "Unable to authenticate. Please check the AAF credentials against namespace.");
212             // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
213             // for specific time.
214         }
215         /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
216                         Arrays.asList(MediaType.APPLICATION_JSON));
217         // AAFResponse output = response.getEntity(AAFResponse.class);
218         response.bufferEntity();
219         String x = response.getEntity(String.class);
220         AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/
221         
222         return false;
223     }
224
225     public static void updateMusicCache(String keyspace, String nameSpace) {
226         logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
227         musicCache.put(keyspace, nameSpace);
228     }
229
230     public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
231         logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
232         Map<String, String> map = new HashMap<>();
233         map.put(userId, password);
234         musicValidateCache.put(nameSpace, map);
235     }
236     
237     public static void updateisAAFCache(String namespace, String isAAF) {
238         appNameCache.put(namespace, isAAF);
239     }
240
241     public static String isAAFApplication(String namespace) throws MusicServiceException {
242         String isAAF = appNameCache.get(namespace);
243         if (isAAF == null) {
244             PreparedQueryObject pQuery = new PreparedQueryObject();
245             pQuery.appendQueryString(
246                             "SELECT is_aaf from admin.keyspace_master where application_name = '"
247                                             + namespace + "' allow filtering");
248             Row rs = null;
249             try {
250                 rs = MusicCore.get(pQuery).one();
251             } catch(InvalidQueryException e) {
252                 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
253                 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
254             }
255             try {
256                 isAAF = String.valueOf(rs.getBool("is_aaf"));
257                 if(isAAF != null)
258                     appNameCache.put(namespace, isAAF);
259             } catch (Exception e) {
260                 logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
261                 e.printStackTrace();
262             }
263         }
264         return isAAF;
265     }
266
267     public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
268         String uuid = null;
269         if (uuid == null) {
270             PreparedQueryObject pQuery = new PreparedQueryObject();
271             pQuery.appendQueryString(
272                             "SELECT uuid from admin.keyspace_master where keyspace_name = '"
273                                             + keyspace + "' allow filtering");
274             Row rs = MusicCore.get(pQuery).one();
275             try {
276                 uuid = rs.getUUID("uuid").toString();
277             } catch (Exception e) {
278                 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
279                 e.printStackTrace();
280             }
281         }
282         return uuid;
283     }
284
285     public static String getAppName(String keyspace) throws MusicServiceException {
286         String appName = null;
287         PreparedQueryObject pQuery = new PreparedQueryObject();
288         pQuery.appendQueryString(
289                         "SELECT application_name from admin.keyspace_master where keyspace_name = '"
290                                         + keyspace + "' allow filtering");
291         Row rs = MusicCore.get(pQuery).one();
292         try {
293             appName = rs.getString("application_name");
294         } catch (Exception e) {
295                 logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
296             e.printStackTrace();
297         }
298         return appName;
299     }
300
301     public static String generateUUID() {
302         String uuid = UUID.randomUUID().toString();
303         logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
304         return uuid;
305     }
306
307     public static Map<String, Object> validateRequest(String nameSpace, String userId,
308                     String password, String keyspace, String aid, String operation) {
309         Map<String, Object> resultMap = new HashMap<>();
310         if (!"createKeySpace".equals(operation)) {
311             if (nameSpace == null) {
312                 resultMap.put("Exception", "Application namespace is mandatory.");
313             }
314         }
315         return resultMap;
316
317     }
318
319     public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
320         Map<String, Object> resultMap = new HashMap<>();
321         if (ns == null || userId == null || password == null) {
322                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
323                 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
324             resultMap.put("Exception",
325                             "One or more required headers appName(ns), userId, password is missing. Please check.");
326             return resultMap;
327         }
328         PreparedQueryObject queryObject = new PreparedQueryObject();
329         queryObject.appendQueryString(
330                         "select * from admin.keyspace_master where application_name = ? allow filtering");
331         try {
332                 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
333         } catch(Exception e) {
334                 resultMap.put("Exception",
335                     "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
336                 return resultMap;
337         }
338         Row rs = null;
339                 try {
340                         rs = MusicCore.get(queryObject).one();
341                 } catch (MusicServiceException e) {
342                         // TODO Auto-generated catch block
343                         e.printStackTrace();
344                         resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
345                         return resultMap;
346         } catch (InvalidQueryException e) {
347             logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
348             resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
349             return resultMap;
350         }
351         if (rs == null) {
352             logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
353             resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
354         } else {
355             if(!(rs.getString("username").equals(userId)) || !(rs.getString("password").equals(password))) {
356                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
357                 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
358                 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
359                 return resultMap;
360             }
361         }
362         return resultMap;
363     }
364
365     public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
366            String keyspace) {
367         Map<String, Object> resultMap = new HashMap<>();
368         if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null) 
369                 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
370             if(!musicCache.get(keyspace).equals(nameSpace)) {
371                 resultMap.put("Exception", "Namespace and keyspace doesn't match");
372                 return resultMap;
373             }
374             if(!musicValidateCache.get(nameSpace).get(userId).equals(password)) {
375                 resultMap.put("Exception", "Namespace, userId and password doesn't match");
376                 return resultMap;
377             }
378             return resultMap;
379         }
380         PreparedQueryObject queryObject = new PreparedQueryObject();
381         queryObject.appendQueryString(
382                         "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
383         try {
384             queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
385         } catch (Exception e) {
386             e.printStackTrace();
387         }
388         Row rs = null;
389         try {
390             rs = MusicCore.get(queryObject).one();
391         } catch (MusicServiceException e) {
392             e.printStackTrace();
393             resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
394             return resultMap;
395         }
396         if(rs == null) {
397             resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
398             return resultMap;
399         }
400         else {
401             String user = rs.getString("username");
402             String pwd = rs.getString("password");
403             String ns = rs.getString("application_name");
404             if(!ns.equals(nameSpace)) {
405             resultMap.put("Exception", "Namespace and keyspace doesn't match");
406             return resultMap;
407             }
408             if(!user.equals(userId)) {
409                 resultMap.put("Exception", "Invalid userId :"+userId);
410                 return resultMap;
411             }
412             if(!pwd.equals(password)) {
413                 resultMap.put("Exception", "Invalid password");
414                 return resultMap;
415             }
416         }
417         CachingUtil.updateMusicCache(keyspace, nameSpace);
418         CachingUtil.updateMusicValidateCache(nameSpace, userId, password);
419         return resultMap;
420     }
421 }