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