2 * ============LICENSE_START==========================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * ============LICENSE_END=============================================
20 * ====================================================================
22 package org.onap.music.main;
24 import java.util.Arrays;
25 import java.util.Calendar;
26 import java.util.HashMap;
27 import java.util.Iterator;
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;
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;
53 * All Caching related logic is handled by this class and a schedule cron runs to update cache.
58 public class CachingUtil implements Runnable {
60 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
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 CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
66 private static Map<String, Number> userAttempts = new HashMap<>();
67 private static Map<String, Calendar> lastFailedTime = new HashMap<>();
69 public boolean isCacheRefreshNeeded() {
70 if (aafCache.get("initBlankMap") == null)
75 public void initializeMusicCache() {
76 logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
77 musicCache.put("isInitialized", "true");
80 public void initializeAafCache() throws MusicServiceException {
81 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
83 String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
84 PreparedQueryObject pQuery = new PreparedQueryObject();
85 pQuery.appendQueryString(query);
87 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
88 } catch (Exception e1) {
89 logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
92 ResultSet rs = MusicCore.get(pQuery);
93 Iterator<Row> it = rs.iterator();
94 Map<String, String> map = null;
95 while (it.hasNext()) {
97 String nameSpace = row.getString("keyspace_name");
98 String userId = row.getString("username");
99 String password = row.getString("password");
100 String keySpace = row.getString("application_name");
102 userAttempts.put(nameSpace, 0);
103 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
104 if (responseObj.getNs().size() > 0) {
105 map = new HashMap<>();
106 map.put(userId, password);
107 aafCache.put(nameSpace, map);
108 musicCache.put(keySpace, nameSpace);
109 logger.debug("Cronjob: Cache Updated with AAF response for namespace "
112 } catch (Exception e) {
113 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
114 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
123 logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
125 initializeAafCache();
126 } catch (MusicServiceException e) {
127 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
131 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
132 String keySpace) throws Exception {
134 if (aafCache.get(nameSpace) != null) {
135 if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) {
136 logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
137 } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
138 logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
139 // reset invalid attempts to 0
140 userAttempts.put(nameSpace, 0);
143 // call AAF update cache with new password
144 if (userAttempts.get(nameSpace) == null)
145 userAttempts.put(nameSpace, 0);
146 if ((Integer) userAttempts.get(nameSpace) >= 3) {
147 logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
148 logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
149 Calendar calendar = Calendar.getInstance();
150 long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
151 logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
152 if( delayTime > 120000) {
153 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
154 userAttempts.put(nameSpace, 0);
156 logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
157 throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
160 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
161 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
165 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
166 if (responseObj.getNs().size() > 0) {
167 if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
168 //Map<String, String> map = new HashMap<>();
169 //map.put(userId, password);
170 //aafCache.put(nameSpace, map);
174 logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
178 private static AAFResponse triggerAAF(String nameSpace, String userId, String password)
180 if (MusicUtil.getAafEndpointUrl() == null) {
181 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
182 throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
184 Client client = Client.create();
185 // WebResource webResource =
186 // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
187 WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
188 String plainCreds = userId + ":" + password;
189 byte[] plainCredsBytes = plainCreds.getBytes();
190 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
191 String base64Creds = new String(base64CredsBytes);
193 ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
194 .header("Authorization", "Basic " + base64Creds)
195 .header("content-type", "application/json").get(ClientResponse.class);
196 if (response.getStatus() != 200) {
197 if (userAttempts.get(nameSpace) == null)
198 userAttempts.put(nameSpace, 0);
199 if ((Integer) userAttempts.get(nameSpace) >= 2) {
200 lastFailedTime.put(nameSpace, Calendar.getInstance());
201 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
203 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
205 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
207 "Unable to authenticate. Please check the AAF credentials against namespace.");
208 // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
209 // for specific time.
211 response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
212 Arrays.asList(MediaType.APPLICATION_JSON));
213 // AAFResponse output = response.getEntity(AAFResponse.class);
214 response.bufferEntity();
215 String x = response.getEntity(String.class);
216 AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);
221 public static void updateMusicCache(String keyspace, String nameSpace) {
222 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
223 musicCache.put(keyspace, nameSpace);
226 public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
227 logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
228 Map<String, String> map = new HashMap<>();
229 map.put(userId, password);
230 musicValidateCache.put(nameSpace, map);
233 public static void updateisAAFCache(String namespace, String isAAF) {
234 appNameCache.put(namespace, isAAF);
237 public static String isAAFApplication(String namespace) throws MusicServiceException {
238 String isAAF = appNameCache.get(namespace);
240 PreparedQueryObject pQuery = new PreparedQueryObject();
241 pQuery.appendQueryString(
242 "SELECT is_aaf from admin.keyspace_master where application_name = '"
243 + namespace + "' allow filtering");
244 Row rs = MusicCore.get(pQuery).one();
246 isAAF = String.valueOf(rs.getBool("is_aaf"));
248 appNameCache.put(namespace, isAAF);
249 } catch (Exception e) {
250 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
257 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
260 PreparedQueryObject pQuery = new PreparedQueryObject();
261 pQuery.appendQueryString(
262 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
263 + keyspace + "' allow filtering");
264 Row rs = MusicCore.get(pQuery).one();
266 uuid = rs.getUUID("uuid").toString();
267 } catch (Exception e) {
268 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
275 public static String getAppName(String keyspace) throws MusicServiceException {
276 String appName = null;
277 PreparedQueryObject pQuery = new PreparedQueryObject();
278 pQuery.appendQueryString(
279 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
280 + keyspace + "' allow filtering");
281 Row rs = MusicCore.get(pQuery).one();
283 appName = rs.getString("application_name");
284 } catch (Exception e) {
285 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
291 public static String generateUUID() {
292 String uuid = UUID.randomUUID().toString();
293 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
297 public static Map<String, Object> validateRequest(String nameSpace, String userId,
298 String password, String keyspace, String aid, String operation) {
299 Map<String, Object> resultMap = new HashMap<>();
300 if (!"createKeySpace".equals(operation)) {
301 if (nameSpace == null) {
302 resultMap.put("Exception", "Application namespace is mandatory.");
309 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
310 Map<String, Object> resultMap = new HashMap<>();
311 if (ns == null || userId == null || password == null) {
312 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
313 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
314 resultMap.put("Exception",
315 "One or more required headers appName(ns), userId, password is missing. Please check.");
318 PreparedQueryObject queryObject = new PreparedQueryObject();
319 queryObject.appendQueryString(
320 "select * from admin.keyspace_master where application_name = ? allow filtering");
322 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
323 } catch(Exception e) {
324 resultMap.put("Exception",
325 "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
330 rs = MusicCore.get(queryObject).one();
331 } catch (MusicServiceException e) {
332 // TODO Auto-generated catch block
334 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
338 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
339 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
341 if(!(rs.getString("username").equals(userId)) || !(rs.getString("password").equals(password))) {
342 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
343 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
344 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
351 public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
353 Map<String, Object> resultMap = new HashMap<>();
354 if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null)
355 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
356 if(!musicCache.get(keyspace).equals(nameSpace)) {
357 resultMap.put("Exception", "Namespace and keyspace doesn't match");
360 if(!musicValidateCache.get(nameSpace).get(userId).equals(password)) {
361 resultMap.put("Exception", "Namespace, userId and password doesn't match");
366 PreparedQueryObject queryObject = new PreparedQueryObject();
367 queryObject.appendQueryString(
368 "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
370 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
371 } catch (Exception e) {
376 rs = MusicCore.get(queryObject).one();
377 } catch (MusicServiceException e) {
379 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
383 resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
387 String user = rs.getString("username");
388 String pwd = rs.getString("password");
389 String ns = rs.getString("application_name");
390 if(!ns.equals(nameSpace)) {
391 resultMap.put("Exception", "Namespace and keyspace doesn't match");
394 if(!user.equals(userId)) {
395 resultMap.put("Exception", "Invalid userId :"+userId);
398 if(!pwd.equals(password)) {
399 resultMap.put("Exception", "Invalid password");
403 CachingUtil.updateMusicCache(keyspace, nameSpace);
404 CachingUtil.updateMusicValidateCache(nameSpace, userId, password);