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