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.exceptions.MusicServiceException;
41 import com.att.eelf.configuration.EELFLogger;
42 import com.datastax.driver.core.DataType;
43 import com.datastax.driver.core.ResultSet;
44 import com.datastax.driver.core.Row;
45 import com.sun.jersey.api.client.Client;
46 import com.sun.jersey.api.client.ClientResponse;
47 import com.sun.jersey.api.client.WebResource;
50 * All Caching related logic is handled by this class and a schedule cron runs to update cache.
55 public class CachingUtil implements Runnable {
57 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
59 private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
60 private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
61 private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
62 private static Map<String, Number> userAttempts = new HashMap<>();
63 private static Map<String, Calendar> lastFailedTime = new HashMap<>();
65 public boolean isCacheRefreshNeeded() {
66 if (aafCache.get("initBlankMap") == null)
71 public void initializeMusicCache() {
72 logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
73 musicCache.put("isInitialized", "true");
76 public void initializeAafCache() throws MusicServiceException {
77 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
79 String query = "SELECT application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
80 PreparedQueryObject pQuery = new PreparedQueryObject();
81 pQuery.appendQueryString(query);
83 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
84 } catch (Exception e1) {
86 logger.error(EELFLoggerDelegate.errorLogger,"Exception is "+ e1.getMessage() + "during initalizeAafCache");
88 ResultSet rs = MusicCore.get(pQuery);
89 Iterator<Row> it = rs.iterator();
90 Map<String, String> map = null;
91 while (it.hasNext()) {
93 String nameSpace = row.getString("keyspace_name");
94 String userId = row.getString("username");
95 String password = row.getString("password");
96 String keySpace = row.getString("application_name");
98 userAttempts.put(nameSpace, 0);
99 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
100 if (responseObj.getNs().size() > 0) {
101 map = new HashMap<>();
102 map.put(userId, password);
103 aafCache.put(nameSpace, map);
104 musicCache.put(nameSpace, keySpace);
105 logger.debug("Cronjob: Cache Updated with AAF response for namespace "
108 } catch (Exception e) {
109 // TODO Auto-generated catch block
111 logger.error("Something at AAF was changed for ns: " + nameSpace
112 + ". So not updating Cache for the namespace. ");
113 logger.error("Exception is " + e.getMessage());
121 logger.debug("Scheduled task invoked. Refreshing Cache...");
123 initializeAafCache();
124 } catch (MusicServiceException e) {
125 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
129 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
130 String keySpace) throws Exception {
132 if (aafCache.get(nameSpace) != null) {
133 if (!musicCache.get(nameSpace).equals(keySpace)) {
134 logger.debug("Create new application for the same namespace.");
135 } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
136 logger.debug("Authenticated with cache value..");
137 // reset invalid attempts to 0
138 userAttempts.put(nameSpace, 0);
141 // call AAF update cache with new password
142 if (userAttempts.get(nameSpace) == null)
143 userAttempts.put(nameSpace, 0);
144 if ((Integer) userAttempts.get(nameSpace) >= 3) {
145 logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
146 logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
147 Calendar calendar = Calendar.getInstance();
148 long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
149 logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
150 if( delayTime > 120000) {
151 logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
152 userAttempts.put(nameSpace, 0);
154 throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
157 logger.error(EELFLoggerDelegate.errorLogger,"Cache not authenticated..");
158 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
162 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
163 if (responseObj.getNs().size() > 0) {
164 if (responseObj.getNs().get(0).getAdmin().contains(userId))
168 logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
172 private static AAFResponse triggerAAF(String nameSpace, String userId, String password)
174 if (MusicUtil.getAafEndpointUrl() == null) {
175 throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
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);
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));
196 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
198 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
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.
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);
213 public static Map<String, Object> authenticateAIDUser(String aid, String keyspace)
215 Map<String, Object> resultMap = new HashMap<>();
218 * if(aid == null || aid.length() == 0) { resultMap.put("Exception Message",
219 * "AID is missing for the keyspace requested."); //create a new AID ?? } else
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();
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."
239 if (!musicCache.get(keyspace).toString().equals(aid)) {
240 resultMap.put("Exception Message",
241 "Unauthorized operation. Invalid AID for the keyspace");
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");
250 resultMap.put("aid", uuid);
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);
259 public static void updateisAAFCache(String namespace, String isAAF) {
260 appNameCache.put(namespace, isAAF);
263 public static Boolean isAAFApplication(String namespace) throws MusicServiceException {
265 String isAAF = appNameCache.get(namespace);
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();
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());
282 return Boolean.valueOf(isAAF);
285 public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
286 String uuid = musicCache.get(keyspace);
288 PreparedQueryObject pQuery = new PreparedQueryObject();
289 pQuery.appendQueryString(
290 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
291 + keyspace + "' allow filtering");
292 Row rs = MusicCore.get(pQuery).one();
294 uuid = rs.getUUID("uuid").toString();
295 musicCache.put(keyspace, uuid);
296 } catch (Exception e) {
297 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
304 public static String getAppName(String keyspace) throws MusicServiceException {
305 String appName = null;
306 PreparedQueryObject pQuery = new PreparedQueryObject();
307 pQuery.appendQueryString(
308 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
309 + keyspace + "' allow filtering");
310 Row rs = MusicCore.get(pQuery).one();
312 appName = rs.getString("application_name");
313 } catch (Exception e) {
314 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
320 public static String generateUUID() {
321 String uuid = UUID.randomUUID().toString();
322 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
326 public static Map<String, Object> validateRequest(String nameSpace, String userId,
327 String password, String keyspace, String aid, String operation) {
328 Map<String, Object> resultMap = new HashMap<>();
329 if (!"createKeySpace".equals(operation)) {
330 if (nameSpace == null) {
331 resultMap.put("Exception", "Application namespace is mandatory.");
338 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password)
340 Map<String, Object> resultMap = new HashMap<>();
341 if (ns == null || userId == null || password == null) {
342 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
343 resultMap.put("Exception",
344 "One or more required headers appName(ns), userId, password is missing. Please check.");
347 PreparedQueryObject queryObject = new PreparedQueryObject();
348 queryObject.appendQueryString(
349 "select * from admin.keyspace_master where application_name=? and username=? allow filtering");
350 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
351 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
352 Row rs = MusicCore.get(queryObject).one();
354 logger.error(EELFLoggerDelegate.errorLogger,"Namespace and UserId doesn't match. namespace: "+ns+" and userId: "+userId);
356 resultMap.put("Exception", "Namespace and UserId doesn't match. namespace: "+ns+" and userId: "+userId);
358 boolean is_aaf = rs.getBool("is_aaf");
359 String keyspace = rs.getString("keyspace_name");
361 if (!keyspace.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
362 logger.error(EELFLoggerDelegate.errorLogger,"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.");