0265d039411f9a68a9e9c0e177dad548f32832e8
[music.git] / src / main / java / org / onap / music / rest / RestMusicAdminAPI.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.rest;
23
24
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.UUID;
30 import javax.servlet.http.HttpServletResponse;
31 import javax.ws.rs.Consumes;
32 import javax.ws.rs.DELETE;
33 import javax.ws.rs.POST;
34 import javax.ws.rs.PUT;
35 import javax.ws.rs.Path;
36 import javax.ws.rs.Produces;
37 import javax.ws.rs.core.Context;
38 import javax.ws.rs.core.MediaType;
39 import org.onap.music.datastore.PreparedQueryObject;
40 import org.onap.music.datastore.jsonobjects.JsonOnboard;
41 import org.onap.music.eelf.logging.EELFLoggerDelegate;
42 import org.onap.music.main.CachingUtil;
43 import org.onap.music.main.MusicCore;
44 import org.onap.music.main.MusicUtil;
45 import com.datastax.driver.core.DataType;
46 import com.datastax.driver.core.ResultSet;
47 import com.datastax.driver.core.Row;
48 import io.swagger.annotations.Api;
49 import io.swagger.annotations.ApiOperation;
50
51 @Path("/v{version: [0-9]+}/admin")
52 // @Path("/admin")
53 @Api(value = "Admin Api", hidden = true)
54 public class RestMusicAdminAPI {
55     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class);
56
57     /*
58      * API to onboard an application with MUSIC. This is the mandatory first step.
59      * 
60      */
61     @POST
62     @Path("/onboardAppWithMusic")
63     @ApiOperation(value = "Onboard application", response = String.class)
64     @Consumes(MediaType.APPLICATION_JSON)
65     @Produces(MediaType.APPLICATION_JSON)
66     public Map<String, Object> onboardAppWithMusic(JsonOnboard jsonObj,
67                     @Context HttpServletResponse response) throws Exception {
68         Map<String, Object> resultMap = new HashMap<>();
69         String appName = jsonObj.getAppname();
70         String userId = jsonObj.getUserId();
71         String isAAF = jsonObj.getIsAAF();
72         String password = jsonObj.getPassword();
73         response.addHeader("X-latestVersion", MusicUtil.getVersion());
74         if (appName == null || userId == null || isAAF == null || password == null) {
75             resultMap.put("Exception",
76                             "Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing.");
77             return resultMap;
78         }
79
80         PreparedQueryObject pQuery = new PreparedQueryObject();
81         pQuery.appendQueryString(
82                         "select uuid from admin.keyspace_master where application_name = ? allow filtering");
83         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
84         ResultSet rs = MusicCore.get(pQuery);
85         if (!rs.all().isEmpty()) {
86             resultMap.put("Exception", "Application " + appName
87                             + " has already been onboarded. Please contact admin.");
88             return resultMap;
89         }
90
91         pQuery = new PreparedQueryObject();
92         String uuid = CachingUtil.generateUUID();
93         pQuery.appendQueryString(
94                         "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
95                                         + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)");
96         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
97         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),
98                         MusicUtil.DEFAULTKEYSPACENAME));
99         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
100         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
101         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), password));
102         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
103         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
104
105         String returnStr = MusicCore.eventualPut(pQuery).toString();
106         if (returnStr.contains("Failure")) {
107             resultMap.put("Exception",
108                             "Oops. Something wrong with onboarding process. Please retry later or contact admin.");
109             return resultMap;
110         }
111         CachingUtil.updateisAAFCache(appName, isAAF);
112         resultMap.put("Success", "Your application " + appName + " has been onboarded with MUSIC.");
113         resultMap.put("Generated AID", uuid);
114         return resultMap;
115     }
116    
117     
118     @POST
119     @Path("/search")
120     @ApiOperation(value = "Search Onboard application", response = String.class)
121     @Consumes(MediaType.APPLICATION_JSON)
122     @Produces(MediaType.APPLICATION_JSON)
123     public Map<String, Object> getOnboardedInfoSearch(
124                                 JsonOnboard jsonObj,
125                     @Context HttpServletResponse response) throws Exception {
126         Map<String, Object> resultMap = new HashMap<>();
127
128         response.addHeader("X-latestVersion", MusicUtil.getVersion());
129         String appName = jsonObj.getAppname();
130         String uuid = jsonObj.getAid();
131         String isAAF = jsonObj.getIsAAF();
132         
133         if (appName == null && uuid == null && isAAF == null) {
134             resultMap.put("Exception",
135                             "Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF.");
136             return resultMap;
137         }
138
139         PreparedQueryObject pQuery = new PreparedQueryObject();
140         String cql = "select uuid, keyspace_name from admin.keyspace_master where ";
141         if (appName != null)
142             cql = cql + "application_name = ? AND ";
143         if (uuid != null)
144             cql = cql + "uuid = ? AND ";
145         if(isAAF != null)
146         cql = cql + "is_aaf = ?";
147         
148         if(cql.endsWith("AND "))
149                 cql = cql.trim().substring(0, cql.length()-4);
150         System.out.println("Query is: "+cql);
151         cql = cql + " allow filtering";
152         System.out.println("Get OnboardingInfo CQL: " + cql);
153         pQuery.appendQueryString(cql);
154         if (appName != null)
155             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
156         if (uuid != null)
157             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
158         if (isAAF != null)
159                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), Boolean.parseBoolean(isAAF)));
160         ResultSet rs = MusicCore.get(pQuery);
161         Iterator<Row> it = rs.iterator();
162         while (it.hasNext()) {
163             Row row = (Row) it.next();
164             resultMap.put( row.getUUID("uuid").toString(),row.getString("keyspace_name"));
165         }
166         if (resultMap.isEmpty())
167             resultMap.put("ERROR", "Application is not onboarded. Please contact admin.");
168         return resultMap;
169     }
170
171
172     @DELETE
173     @Path("/onboardAppWithMusic")
174     @ApiOperation(value = "Delete Onboard application", response = String.class)
175     @Consumes(MediaType.APPLICATION_JSON)
176     @Produces(MediaType.APPLICATION_JSON)
177     public Map<String, Object> deleteOnboardApp(JsonOnboard jsonObj,
178                     @Context HttpServletResponse response) throws Exception {
179         Map<String, Object> resultMap = new HashMap<>();
180         response.addHeader("X-latestVersion", MusicUtil.getVersion());
181         String appName = jsonObj.getAppname();
182         String aid = jsonObj.getAid();
183         PreparedQueryObject pQuery = new PreparedQueryObject();
184         String consistency = MusicUtil.EVENTUAL;;
185         if (appName == null && aid == null) {
186             resultMap.put("Exception", "Please make sure either appName(ns) or Aid is present");
187             return resultMap;
188         }
189         if (aid != null) {
190                         pQuery.appendQueryString("SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?");
191                         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
192                         UUID.fromString(aid)));
193                         Row row = MusicCore.get(pQuery).one();
194                         if(row!=null) {
195                                 String ks = row.getString("keyspace_name");
196                                 if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
197                                         PreparedQueryObject queryObject = new PreparedQueryObject();
198                                         queryObject.appendQueryString("DROP KEYSPACE " + ks + ";");
199                                         MusicCore.nonKeyRelatedPut(queryObject, consistency);
200                                 }
201                         }
202                         pQuery = new PreparedQueryObject();
203                 pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ? IF EXISTS");
204                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
205                                 UUID.fromString(aid)));
206                 boolean result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
207                 if (result) {
208                     resultMap.put("Success", "Your application has been deleted successfully");
209                 } else {
210                     resultMap.put("Exception",
211                                     "Oops. Spomething went wrong. Please make sure Aid is correct or Application is onboarded");
212                 }
213                 return resultMap;    
214         }
215         
216         
217         
218                 
219         pQuery.appendQueryString(
220                         "select uuid from admin.keyspace_master where application_name = ? allow filtering");
221         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
222         ResultSet rs = MusicCore.get(pQuery);
223         List<Row> rows = rs.all();
224         String uuid = null;
225         if (rows.size() == 0) {
226             resultMap.put("Exception",
227                             "Application not found. Please make sure Application exists.");
228             return resultMap;
229         } else if (rows.size() == 1) {
230             uuid = rows.get(0).getUUID("uuid").toString();
231             pQuery = new PreparedQueryObject();
232             pQuery.appendQueryString("SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?");
233                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
234                     UUID.fromString(uuid)));
235                         Row row = MusicCore.get(pQuery).one();
236                         String ks = row.getString("keyspace_name");
237                         if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
238                                 PreparedQueryObject queryObject = new PreparedQueryObject();
239                                 queryObject.appendQueryString("DROP KEYSPACE " + ks + ";");
240                                 MusicCore.nonKeyRelatedPut(queryObject, consistency);
241                         }
242                 
243             pQuery = new PreparedQueryObject();
244             pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?");
245             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
246                             UUID.fromString(uuid)));
247             MusicCore.eventualPut(pQuery);
248             resultMap.put("Success", "Your application " + appName + " has been deleted.");
249             return resultMap;
250         } else {
251             resultMap.put("Failure", "More than one Aid exists for this application, so please provide Aid.");
252         }
253
254         return resultMap;
255     }
256
257
258     @PUT
259     @Path("/onboardAppWithMusic")
260     @ApiOperation(value = "Update Onboard application", response = String.class)
261     @Consumes(MediaType.APPLICATION_JSON)
262     @Produces(MediaType.APPLICATION_JSON)
263     public Map<String, Object> updateOnboardApp(JsonOnboard jsonObj,
264                     @Context HttpServletResponse response) throws Exception {
265         Map<String, Object> resultMap = new HashMap<>();
266         response.addHeader("X-latestVersion", MusicUtil.getVersion());
267         String aid = jsonObj.getAid();
268         String appName = jsonObj.getAppname();
269         String userId = jsonObj.getUserId();
270         String isAAF = jsonObj.getIsAAF();
271         String password = jsonObj.getPassword();
272         String consistency = "eventual";
273         PreparedQueryObject pQuery;
274
275         if (aid == null) {
276             resultMap.put("Exception", "Please make sure Aid is present");
277             return resultMap;
278         }
279
280         if (appName == null && userId == null && password == null && isAAF == null) {
281             resultMap.put("Exception",
282                             "No parameters found to update. Please update atleast one parameter.");
283             return resultMap;
284         }
285         
286         if(appName!=null) {     
287                 pQuery = new PreparedQueryObject();
288                 pQuery.appendQueryString(
289                                 "select uuid from admin.keyspace_master where application_name = ? allow filtering");
290                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
291                 ResultSet rs = MusicCore.get(pQuery);
292                 if (!rs.all().isEmpty()) {
293                     resultMap.put("Exception", "Application " + appName
294                                     + " has already been onboarded. Please contact admin.");
295                     return resultMap;
296                 }
297         }
298         
299                 pQuery = new PreparedQueryObject();
300                 StringBuilder preCql = new StringBuilder("UPDATE admin.keyspace_master SET ");
301                 if (appName != null)
302                     preCql.append(" application_name = ?,");
303                 if (userId != null)
304                     preCql.append(" username = ?,");
305                 if (password != null)
306                     preCql.append(" password = ?,");
307                 if (isAAF != null)
308                     preCql.append(" is_aaf = ?,");
309                 preCql.deleteCharAt(preCql.length() - 1);
310                 preCql.append(" WHERE uuid = ? IF EXISTS");
311                 pQuery.appendQueryString(preCql.toString());
312                 if (appName != null)
313                     pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
314                 if (userId != null)
315                     pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
316                 if (password != null)
317                     pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), password));
318                 if (isAAF != null)
319                     pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
320         
321                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid)));
322                 boolean result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
323         
324                 if (result) {
325                     resultMap.put("Success", "Your application has been updated successfully");
326                 } else {
327                     resultMap.put("Exception",
328                                     "Oops. Spomething went wrong. Please make sure Aid is correct and application is onboarded");
329                 }
330                 
331         return resultMap;
332     }
333 }