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.apache.log4j.Logger;
36 import org.codehaus.jackson.map.ObjectMapper;
37 import org.onap.music.datastore.jsonobjects.AAFResponse;
38 import com.att.eelf.configuration.EELFLogger;
39 import com.att.eelf.configuration.EELFManager;
40 import org.onap.music.datastore.PreparedQueryObject;
41 import com.datastax.driver.core.DataType;
42 import com.datastax.driver.core.ResultSet;
43 import com.datastax.driver.core.Row;
44 import com.sun.jersey.api.client.Client;
45 import com.sun.jersey.api.client.ClientResponse;
46 import com.sun.jersey.api.client.WebResource;
49 * All Caching related logic is handled by this class and a schedule cron runs to update cache.
54 public class CachingUtil implements Runnable {
56 private static EELFLogger logger = EELFManager.getInstance().getLogger(CachingUtil.class);
58 private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
59 private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
60 private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
61 private static Map<String, Number> userAttempts = new HashMap<>();
62 private static Map<String, Calendar> lastFailedTime = new HashMap<>();
64 public boolean isCacheRefreshNeeded() {
65 if (aafCache.get("initBlankMap") == null)
70 public void initializeMusicCache() {
71 logger.info("Initializing Music Cache...");
72 musicCache.put("isInitialized", "true");
75 public void initializeAafCache() {
76 logger.info("Resetting and initializing AAF Cache...");
79 // loop through aafCache ns .. only the authenticated ns will be re cached. and non
80 // authenticated will wait for user to retry.
81 String query = "SELECT application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
82 PreparedQueryObject pQuery = new PreparedQueryObject();
83 pQuery.appendQueryString(query);
85 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
86 } catch (Exception e1) {
88 logger.error("Exception is " + e1.getMessage() + "during initalizeAafCache");
90 ResultSet rs = MusicCore.get(pQuery);
91 Iterator<Row> it = rs.iterator();
92 Map<String, String> map = null;
93 while (it.hasNext()) {
95 String nameSpace = row.getString("keyspace_name");
96 String userId = row.getString("username");
97 String password = row.getString("password");
98 String keySpace = row.getString("application_name");
100 userAttempts.put(nameSpace, 0);
101 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
102 if (responseObj.getNs().size() > 0) {
103 map = new HashMap<>();
104 map.put(userId, password);
105 aafCache.put(nameSpace, map);
106 musicCache.put(nameSpace, keySpace);
107 logger.debug("Cronjob: Cache Updated with AAF response for namespace "
110 } catch (Exception e) {
111 // TODO Auto-generated catch block
113 logger.error("Something at AAF was changed for ns: " + nameSpace
114 + ". So not updating Cache for the namespace. ");
115 logger.error("Exception is " + e.getMessage());
123 logger.debug("Scheduled task invoked. Refreshing Cache...");
124 initializeAafCache();
127 public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
128 String keySpace) throws Exception {
130 if (aafCache.get(nameSpace) != null) {
131 if (!musicCache.get(nameSpace).equals(keySpace)) {
132 logger.debug("Create new application for the same namespace.");
133 } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
134 logger.debug("Authenticated with cache value..");
135 // reset invalid attempts to 0
136 userAttempts.put(nameSpace, 0);
139 // call AAF update cache with new password
140 if (userAttempts.get(nameSpace) == null)
141 userAttempts.put(nameSpace, 0);
142 if ((Integer) userAttempts.get(nameSpace) >= 3) {
143 logger.info("Reached max attempts. Checking if time out..");
144 logger.info("Failed time: " + lastFailedTime.get(nameSpace).getTime());
145 Calendar calendar = Calendar.getInstance();
146 long delayTime = (calendar.getTimeInMillis()
147 - lastFailedTime.get(nameSpace).getTimeInMillis());
148 logger.info("Delayed time: " + delayTime);
149 if (delayTime > 120000) {
150 logger.info("Resetting failed attempt.");
151 userAttempts.put(nameSpace, 0);
154 "No more attempts allowed. Please wait for atleast 2 min.");
157 logger.error("Cache not authenticated..");
158 logger.info("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("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) {
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());
280 return Boolean.valueOf(isAAF);
283 public static String getUuidFromMusicCache(String keyspace) {
284 String uuid = musicCache.get(keyspace);
286 PreparedQueryObject pQuery = new PreparedQueryObject();
287 pQuery.appendQueryString(
288 "SELECT uuid from admin.keyspace_master where keyspace_name = '"
289 + keyspace + "' allow filtering");
290 Row rs = MusicCore.get(pQuery).one();
292 uuid = rs.getUUID("uuid").toString();
293 musicCache.put(keyspace, uuid);
294 } catch (Exception e) {
295 logger.error("Exception occured during uuid retrieval from DB." + e.getMessage());
302 public static String getAppName(String keyspace) {
303 String appName = null;
304 PreparedQueryObject pQuery = new PreparedQueryObject();
305 pQuery.appendQueryString(
306 "SELECT application_name from admin.keyspace_master where keyspace_name = '"
307 + keyspace + "' allow filtering");
308 Row rs = MusicCore.get(pQuery).one();
310 appName = rs.getString("application_name");
311 } catch (Exception e) {
312 logger.error("Exception occured during uuid retrieval from DB." + e.getMessage());
318 public static String generateUUID() {
319 String uuid = UUID.randomUUID().toString();
320 logger.info("New AID generated: " + uuid);
324 public static Map<String, Object> validateRequest(String nameSpace, String userId,
325 String password, String keyspace, String aid, String operation) {
326 Map<String, Object> resultMap = new HashMap<>();
327 if (!"createKeySpace".equals(operation)) {
328 if (nameSpace == null) {
329 resultMap.put("Exception", "Application namespace is mandatory.");
336 public static Map<String, Object> verifyOnboarding(String ns, String userId, String password)
338 Map<String, Object> resultMap = new HashMap<>();
339 if (ns == null || userId == null || password == null) {
340 logger.error("One or more required headers is missing. userId: " + userId
341 + " :: password: " + password);
342 resultMap.put("Exception",
343 "One or more required headers appName(ns), userId, password is missing. Please check.");
346 PreparedQueryObject queryObject = new PreparedQueryObject();
347 queryObject.appendQueryString(
348 "select * from admin.keyspace_master where application_name=? and username=? allow filtering");
349 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
350 queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
351 Row rs = MusicCore.get(queryObject).one();
353 logger.error("Namespace and UserId doesn't match. namespace: " + ns + " and userId: "
355 resultMap.put("Exception", "Application " + ns
356 + " doesn't seem to be Onboarded. Please onboard your application with MUSIC. If already onboarded contact Admin");
358 boolean is_aaf = rs.getBool("is_aaf");
359 String keyspace = rs.getString("keyspace_name");
361 if (!keyspace.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
362 logger.error("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.");