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