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 Map<String, Number> userAttempts = new HashMap<>();
66 private static Map<String, Calendar> lastFailedTime = new HashMap<>();
68 public boolean isCacheRefreshNeeded() {
69 if (aafCache.get("initBlankMap") == null)
74 public void initializeMusicCache() {
75 logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
76 musicCache.put("isInitialized", "true");
79 public void initializeAafCache() throws MusicServiceException {
80 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
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);
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);
91 ResultSet rs = MusicCore.get(pQuery);
92 Iterator<Row> it = rs.iterator();
93 Map<String, String> map = null;
94 while (it.hasNext()) {
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");
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 "
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. ");
122 logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
124 initializeAafCache();
125 } catch (MusicServiceException e) {
126 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
130 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
131 String keySpace) throws Exception {
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);
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);
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.");
159 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
160 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
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);
173 logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
177 private static AAFResponse triggerAAF(String nameSpace, String userId, String password)
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.");
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);
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));
202 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
204 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
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.
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);
220 public static Map<String, Object> authenticateAIDUser(String aid, String keyspace)
222 Map<String, Object> resultMap = new HashMap<>();
225 * if(aid == null || aid.length() == 0) { resultMap.put("Exception Message",
226 * "AID is missing for the keyspace requested."); //create a new AID ?? } else
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();
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."
246 if (!musicCache.get(keyspace).toString().equals(aid)) {
247 resultMap.put("Exception",
248 "Unauthorized operation. Invalid AID for the keyspace");
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");
257 resultMap.put("aid", uuid);
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);
266 public static void updateisAAFCache(String namespace, String isAAF) {
267 appNameCache.put(namespace, isAAF);
270 public static String isAAFApplication(String namespace) throws MusicServiceException {
271 String isAAF = appNameCache.get(namespace);
273 PreparedQueryObject pQuery = new PreparedQueryObject();
274 pQuery.appendQueryString(
275 "SELECT is_aaf from admin.keyspace_master where application_name = '"
276 + namespace + "' allow filtering");
277 Row rs = MusicCore.get(pQuery).one();
279 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);
290 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
291 String uuid = musicCache.get(keyspace);
293 PreparedQueryObject pQuery = new PreparedQueryObject();
294 pQuery.appendQueryString(
295 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
296 + keyspace + "' allow filtering");
297 Row rs = MusicCore.get(pQuery).one();
299 uuid = rs.getUUID("uuid").toString();
300 musicCache.put(keyspace, uuid);
301 } catch (Exception e) {
302 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
309 public static String getAppName(String keyspace) throws MusicServiceException {
310 String appName = null;
311 PreparedQueryObject pQuery = new PreparedQueryObject();
312 pQuery.appendQueryString(
313 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
314 + keyspace + "' allow filtering");
315 Row rs = MusicCore.get(pQuery).one();
317 appName = rs.getString("application_name");
318 } catch (Exception e) {
319 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
325 public static String generateUUID() {
326 String uuid = UUID.randomUUID().toString();
327 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
331 public static Map<String, Object> validateRequest(String nameSpace, String userId,
332 String password, String keyspace, String aid, String operation) {
333 Map<String, Object> resultMap = new HashMap<>();
334 if (!"createKeySpace".equals(operation)) {
335 if (nameSpace == null) {
336 resultMap.put("Exception", "Application namespace is mandatory.");
343 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
344 Map<String, Object> resultMap = new HashMap<>();
345 if (ns == null || userId == null || password == null) {
346 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
347 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
348 resultMap.put("Exception",
349 "One or more required headers appName(ns), userId, password is missing. Please check.");
352 PreparedQueryObject queryObject = new PreparedQueryObject();
353 queryObject.appendQueryString(
354 "select * from admin.keyspace_master where application_name = ? allow filtering");
356 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
357 } catch(Exception e) {
358 resultMap.put("Exception",
359 "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
364 rs = MusicCore.get(queryObject).one();
365 } catch (MusicServiceException e) {
366 // TODO Auto-generated catch block
368 resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
372 logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
373 resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
375 if(!(rs.getString("username").equals(userId)) && !(rs.getString("password").equals("password"))) {
376 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
377 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
378 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
381 boolean is_aaf = rs.getBool("is_aaf");
382 String keyspace = rs.getString("keyspace_name");
384 if (!keyspace.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
385 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.DATAERROR);
386 logger.error(EELFLoggerDelegate.errorLogger,"Non AAF applications are allowed to have only one keyspace per application.");
387 resultMap.put("Exception",
388 "Non AAF applications are allowed to have only one keyspace per application.");