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