More Unit tests for Sonar coverage
[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             resultMap.put("ERROR", "Application is not onboarded. Please contact admin.");
172         return resultMap;
173     }
174
175
176     @DELETE
177     @Path("/onboardAppWithMusic")
178     @ApiOperation(value = "Delete Onboard application", response = String.class)
179     @Consumes(MediaType.APPLICATION_JSON)
180     @Produces(MediaType.APPLICATION_JSON)
181     public Map<String, Object> deleteOnboardApp(JsonOnboard jsonObj,
182                     @Context HttpServletResponse response) throws Exception {
183         Map<String, Object> resultMap = new HashMap<>();
184         response.addHeader("X-latestVersion", MusicUtil.getVersion());
185         String appName = jsonObj.getAppname();
186         String aid = jsonObj.getAid();
187         PreparedQueryObject pQuery = new PreparedQueryObject();
188         String consistency = MusicUtil.EVENTUAL;;
189         if (appName == null && aid == null) {
190             resultMap.put("Exception", "Please make sure either appName(ns) or Aid is present");
191             return resultMap;
192         }
193         if (aid != null) {
194                         pQuery.appendQueryString("SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?");
195                         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
196                         UUID.fromString(aid)));
197                         Row row = MusicCore.get(pQuery).one();
198                         if(row!=null) {
199                                 String ks = row.getString("keyspace_name");
200                                 if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
201                                         PreparedQueryObject queryObject = new PreparedQueryObject();
202                                         queryObject.appendQueryString("DROP KEYSPACE IF EXISTS " + ks + ";");
203                                         MusicCore.nonKeyRelatedPut(queryObject, consistency);
204                                 }
205                         }
206                         pQuery = new PreparedQueryObject();
207                 pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ? IF EXISTS");
208                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
209                                 UUID.fromString(aid)));
210                 boolean result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
211                 if (result) {
212                     resultMap.put("Success", "Your application has been deleted successfully");
213                 } else {
214                     resultMap.put("Exception",
215                                     "Oops. Spomething went wrong. Please make sure Aid is correct or Application is onboarded");
216                 }
217                 return resultMap;    
218         }
219         
220         
221         
222                 
223         pQuery.appendQueryString(
224                         "select uuid from admin.keyspace_master where application_name = ? allow filtering");
225         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
226         ResultSet rs = MusicCore.get(pQuery);
227         List<Row> rows = rs.all();
228         String uuid = null;
229         if (rows.size() == 0) {
230             resultMap.put("Exception",
231                             "Application not found. Please make sure Application exists.");
232             return resultMap;
233         } else if (rows.size() == 1) {
234             uuid = rows.get(0).getUUID("uuid").toString();
235             pQuery = new PreparedQueryObject();
236             pQuery.appendQueryString("SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?");
237                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
238                     UUID.fromString(uuid)));
239                         Row row = MusicCore.get(pQuery).one();
240                         String ks = row.getString("keyspace_name");
241                         if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
242                                 PreparedQueryObject queryObject = new PreparedQueryObject();
243                                 queryObject.appendQueryString("DROP KEYSPACE " + ks + ";");
244                                 MusicCore.nonKeyRelatedPut(queryObject, consistency);
245                         }
246                 
247             pQuery = new PreparedQueryObject();
248             pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?");
249             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
250                             UUID.fromString(uuid)));
251             MusicCore.eventualPut(pQuery);
252             resultMap.put("Success", "Your application " + appName + " has been deleted.");
253             return resultMap;
254         } else {
255             resultMap.put("Failure", "More than one Aid exists for this application, so please provide Aid.");
256         }
257
258         return resultMap;
259     }
260
261
262     @PUT
263     @Path("/onboardAppWithMusic")
264     @ApiOperation(value = "Update Onboard application", response = String.class)
265     @Consumes(MediaType.APPLICATION_JSON)
266     @Produces(MediaType.APPLICATION_JSON)
267     public Map<String, Object> updateOnboardApp(JsonOnboard jsonObj,
268                     @Context HttpServletResponse response) throws Exception {
269         Map<String, Object> resultMap = new HashMap<>();
270         response.addHeader("X-latestVersion", MusicUtil.getVersion());
271         String aid = jsonObj.getAid();
272         String appName = jsonObj.getAppname();
273         String userId = jsonObj.getUserId();
274         String isAAF = jsonObj.getIsAAF();
275         String password = jsonObj.getPassword();
276         String consistency = "eventual";
277         PreparedQueryObject pQuery;
278
279         if (aid == null) {
280             resultMap.put("Exception", "Please make sure Aid is present");
281             return resultMap;
282         }
283
284         if (appName == null && userId == null && password == null && isAAF == null) {
285             resultMap.put("Exception",
286                             "No parameters found to update. Please update atleast one parameter.");
287             return resultMap;
288         }
289         
290         if(appName!=null) {     
291                 pQuery = new PreparedQueryObject();
292                 pQuery.appendQueryString(
293                                 "select uuid from admin.keyspace_master where application_name = ? allow filtering");
294                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
295                 ResultSet rs = MusicCore.get(pQuery);
296                 if (!rs.all().isEmpty()) {
297                     resultMap.put("Exception", "Application " + appName
298                                     + " has already been onboarded. Please contact admin.");
299                     return resultMap;
300                 }
301         }
302         
303                 pQuery = new PreparedQueryObject();
304                 StringBuilder preCql = new StringBuilder("UPDATE admin.keyspace_master SET ");
305                 if (appName != null)
306                     preCql.append(" application_name = ?,");
307                 if (userId != null)
308                     preCql.append(" username = ?,");
309                 if (password != null)
310                     preCql.append(" password = ?,");
311                 if (isAAF != null)
312                     preCql.append(" is_aaf = ?,");
313                 preCql.deleteCharAt(preCql.length() - 1);
314                 preCql.append(" WHERE uuid = ? IF EXISTS");
315                 pQuery.appendQueryString(preCql.toString());
316                 if (appName != null)
317                     pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
318                 if (userId != null)
319                     pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
320                 if (password != null)
321                     pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), password));
322                 if (isAAF != null)
323                     pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
324         
325                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid)));
326                 boolean result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
327         
328                 if (result) {
329                     resultMap.put("Success", "Your application has been updated successfully");
330                 } else {
331                     resultMap.put("Exception",
332                                     "Oops. Spomething went wrong. Please make sure Aid is correct and application is onboarded");
333                 }
334                 
335         return resultMap;
336     }
337 }