Changes Listed below:
[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  * Modifications Copyright (C) 2018 IBM.
8  * Modifications Copyright (c) 2019 Samsung
9  * ================================================================================
10  *  Licensed under the Apache License, Version 2.0 (the "License");
11  *  you may not use this file except in compliance with the License.
12  *  You may obtain a copy of the License at
13  *
14  *     http://www.apache.org/licenses/LICENSE-2.0
15  *
16  *  Unless required by applicable law or agreed to in writing, software
17  *  distributed under the License is distributed on an "AS IS" BASIS,
18  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  *  See the License for the specific language governing permissions and
20  *  limitations under the License.
21  *
22  * ============LICENSE_END=============================================
23  * ====================================================================
24  */
25
26 package org.onap.music.rest;
27
28
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.UUID;
36
37 import javax.ws.rs.Consumes;
38 import javax.ws.rs.DELETE;
39 import javax.ws.rs.GET;
40 import javax.ws.rs.HeaderParam;
41 import javax.ws.rs.POST;
42 import javax.ws.rs.PUT;
43 import javax.ws.rs.Path;
44 import javax.ws.rs.Produces;
45 import javax.ws.rs.core.MediaType;
46 import javax.ws.rs.core.Response;
47 import javax.ws.rs.core.Response.ResponseBuilder;
48 import javax.ws.rs.core.Response.Status;
49
50 import org.mindrot.jbcrypt.BCrypt;
51 import org.onap.music.authentication.CachingUtil;
52 import org.onap.music.authentication.MusicAAFAuthentication;
53 import org.onap.music.authentication.MusicAuthenticator;
54 import org.onap.music.datastore.MusicDataStoreHandle;
55 import org.onap.music.datastore.PreparedQueryObject;
56 import org.onap.music.datastore.jsonobjects.JsonOnboard;
57 import org.onap.music.datastore.jsonobjects.MusicResponse;
58 import org.onap.music.eelf.logging.EELFLoggerDelegate;
59 import org.onap.music.eelf.logging.format.AppMessages;
60 import org.onap.music.eelf.logging.format.ErrorSeverity;
61 import org.onap.music.eelf.logging.format.ErrorTypes;
62 import org.onap.music.exceptions.MusicServiceException;
63 import org.onap.music.main.MusicCore;
64 import org.onap.music.main.MusicUtil;
65 import org.onap.music.main.ResultType;
66 import org.onap.music.response.jsonobjects.JsonResponse;
67 import org.springframework.beans.factory.config.YamlProcessor.ResolutionMethod;
68
69 import com.datastax.driver.core.DataType;
70 import com.datastax.driver.core.KeyspaceMetadata;
71 import com.datastax.driver.core.ResultSet;
72 import com.datastax.driver.core.Row;
73 import com.datastax.driver.core.TableMetadata;
74 import com.sun.xml.bind.v2.TODO;
75
76 import io.swagger.annotations.Api;
77 import io.swagger.annotations.ApiOperation;
78 import io.swagger.annotations.ApiParam;
79 //import java.util.Base64.Encoder;
80 //import java.util.Base64.Decoder;
81
82 @Path("/v2/admin")
83 @Api(value = "Admin Api", hidden = true)
84 public class RestMusicAdminAPI {
85     private static EELFLoggerDelegate logger =
86                     EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class);
87     // Set to true in env like ONAP. Where access to creating and dropping keyspaces exist.    
88     private static final boolean KEYSPACE_ACTIVE = false;
89     
90     private MusicAuthenticator authenticator = new MusicAAFAuthentication();
91
92     /*
93      * API to onboard an application with MUSIC. This is the mandatory first step.
94      *
95      */
96     @POST
97     @Path("/onboardAppWithMusic")
98     @ApiOperation(value = "Onboard application", response = String.class)
99     @Consumes(MediaType.APPLICATION_JSON)
100     @Produces(MediaType.APPLICATION_JSON)
101     public Response onboardAppWithMusic(JsonOnboard jsonObj,
102             @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception {
103         logger.info(EELFLoggerDelegate.errorLogger, "oboarding app");
104         ResponseBuilder response =
105                         Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
106         if (!authenticator.authenticateAdmin(authorization)) {
107             logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
108                     ErrorTypes.AUTHENTICATIONERROR);
109             return response.status(Status.UNAUTHORIZED)
110                     .entity(new JsonResponse(ResultType.FAILURE)
111                             .setError("Unauthorized: Please check admin username,password and try again").toMap())
112                     .build();
113         }
114
115         Map<String, Object> resultMap = new HashMap<>();
116         String appName = jsonObj.getAppname();
117         String userId = jsonObj.getUserId();
118         String password = jsonObj.getPassword();
119         String keyspace_name = jsonObj.getKeyspace();
120         
121         if (appName == null || userId == null ||  password == null || keyspace_name == null) {
122             logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing.", AppMessages.MISSINGINFO,
123                             ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
124             resultMap.put("Exception",
125                             "Unauthorized: Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing.");
126             return response.status(Status.BAD_REQUEST).entity(resultMap).build();
127         }
128
129         PreparedQueryObject pQuery = new PreparedQueryObject();
130     
131         pQuery.appendQueryString(
132             "select uuid from admin.keyspace_master where application_name = ? and keyspace_name = ? allow filtering");
133         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
134         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace_name));
135         ResultSet rs = MusicCore.get(pQuery);
136         if (!rs.all().isEmpty()) {
137             logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA, ErrorSeverity.CRITICAL,
138                 ErrorTypes.GENERALSERVICEERROR);
139             response.status(Status.BAD_REQUEST);
140             return response.entity(new JsonResponse(ResultType.FAILURE)
141                 .setError("Application " + appName + " has already been onboarded. Please contact admin.").toMap())
142                 .build();
143         }
144     
145         pQuery = new PreparedQueryObject();
146         String uuid = MusicUtil.generateUUID();
147         pQuery.appendQueryString(
148                         "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
149                                         + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)");
150         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
151         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),keyspace_name));
152         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
153         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "False"));
154         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt())));
155         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
156         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "true"));
157
158         String returnStr = MusicCore.eventualPut(pQuery).toString();
159         if (returnStr.contains("Failure")) {
160             logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
161             response.status(Status.BAD_REQUEST);
162             return response.entity(new JsonResponse(ResultType.FAILURE).setError("Oops. Something wrong with onboarding process. "
163                     + "Please retry later or contact admin.").toMap()).build();
164         }
165         //CachingUtil.updateisAAFCache(appName, isAAF);
166         resultMap.put("Success", "Your application " + appName + " has been onboarded with MUSIC.");
167         resultMap.put("Generated AID", uuid);
168         return response.status(Status.OK).entity(resultMap).build();
169     }
170
171
172     @POST
173     @Path("/search")
174     @ApiOperation(value = "Search Onboard application", response = String.class)
175     @Consumes(MediaType.APPLICATION_JSON)
176     @Produces(MediaType.APPLICATION_JSON)
177     public Response getOnboardedInfoSearch(JsonOnboard jsonObj,
178             @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception {
179         ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
180         
181         if (!authenticator.authenticateAdmin(authorization)) {
182             logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
183                     ErrorTypes.AUTHENTICATIONERROR);
184             return response.status(Status.UNAUTHORIZED)
185                     .entity(new JsonResponse(ResultType.FAILURE)
186                             .setError("Unauthorized: Please check admin username,password and try again").toMap())
187                     .build();
188         }
189         
190         Map<String, Object> resultMap = new HashMap<>();
191         String appName = jsonObj.getAppname();
192         String uuid = jsonObj.getAid();
193         String isAAF = jsonObj.getIsAAF();
194         if (appName == null && uuid == null && isAAF == null) {
195             logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF.", AppMessages.MISSINGINFO,
196                             ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
197             resultMap.put("Exception",
198                             "Unauthorized: Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF.");
199             return response.status(Status.BAD_REQUEST).entity(resultMap).build();
200         }
201
202         PreparedQueryObject pQuery = new PreparedQueryObject();
203         String cql = "select uuid, keyspace_name from admin.keyspace_master where ";
204         if (appName != null)
205             cql = cql + "application_name = ? AND ";
206         if (uuid != null)
207             cql = cql + "uuid = ? AND ";
208         if (isAAF != null)
209             cql = cql + "is_aaf = ?";
210
211         if (cql.endsWith("AND "))
212             cql = cql.trim().substring(0, cql.length() - 4);
213         logger.info("Query in callback is: " + cql);
214         cql = cql + " allow filtering";
215         pQuery.appendQueryString(cql);
216         if (appName != null)
217             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
218         if (uuid != null)
219             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
220         if (isAAF != null)
221             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(),
222                             Boolean.parseBoolean(isAAF)));
223         ResultSet rs = MusicCore.get(pQuery);
224         Iterator<Row> it = rs.iterator();
225         while (it.hasNext()) {
226             Row row = it.next();
227             resultMap.put(row.getUUID("uuid").toString(), row.getString("keyspace_name"));
228         }
229         if (resultMap.isEmpty()) {
230             if (uuid != null) {
231                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
232                 response.status(Status.BAD_REQUEST);
233                 return response.entity(new JsonResponse(ResultType.FAILURE).setError("Please make sure Aid is correct and application is onboarded.").toMap()).build();
234
235             } else {
236                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
237                 response.status(Status.BAD_REQUEST);
238                 return response.entity(new JsonResponse(ResultType.FAILURE).setError("Application is not onboarded. Please make sure all the information is correct.").toMap()).build();
239             }
240         }
241         return response.status(Status.OK).entity(resultMap).build();
242     }
243
244
245     @DELETE
246     @Path("/onboardAppWithMusic")
247     @ApiOperation(value = "Delete Onboard application", response = String.class)
248     @Consumes(MediaType.APPLICATION_JSON)
249     @Produces(MediaType.APPLICATION_JSON)
250     public Response deleteOnboardApp(JsonOnboard jsonObj,
251             @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception {
252         ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
253         
254         if (!authenticator.authenticateAdmin(authorization)) {
255             logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
256                     ErrorTypes.AUTHENTICATIONERROR);
257             return response.status(Status.UNAUTHORIZED)
258                     .entity(new JsonResponse(ResultType.FAILURE)
259                             .setError("Unauthorized: Please check admin username,password and try again").toMap())
260                     .build();
261         }
262         
263         Map<String, Object> resultMap = new HashMap<>();
264         String appName = jsonObj.getAppname();
265         String aid = jsonObj.getAid();
266         PreparedQueryObject pQuery = new PreparedQueryObject();
267         String consistency = MusicUtil.EVENTUAL;
268         if (appName == null && aid == null) {
269             logger.error(EELFLoggerDelegate.errorLogger, 
270                 "Please make sure either appName(ns) or Aid is present", AppMessages.MISSINGINFO,
271                 ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
272             resultMap.put("Exception", "Please make sure either appName(ns) or Aid is present");
273             return response.status(Status.BAD_REQUEST).entity(resultMap).build();
274         }
275         if (aid != null) {
276             if (MusicUtil.isKeyspaceActive()) {
277                 pQuery.appendQueryString(
278                             "SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?");
279                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
280                             UUID.fromString(aid)));
281                 Row row = MusicCore.get(pQuery).one();
282                 if (row != null) {
283                     String ks = row.getString("keyspace_name");
284                     if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
285                         PreparedQueryObject queryObject = new PreparedQueryObject();
286                         queryObject.appendQueryString("DROP KEYSPACE IF EXISTS " + ks + ";");
287                         MusicCore.nonKeyRelatedPut(queryObject, consistency);
288                     }
289                 }
290             }
291             pQuery = new PreparedQueryObject();
292             pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ? IF EXISTS");
293             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
294                             UUID.fromString(aid)));
295             ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
296             if (result == ResultType.SUCCESS) {
297                 resultMap.put("Success", "Your application has been deleted successfully");
298             } else {
299                 resultMap.put("Exception",
300                     "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded");
301                 logger.error(EELFLoggerDelegate.errorLogger, 
302                     "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded", 
303                     AppMessages.INCORRECTDATA,
304                     ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
305                 return response.status(Status.BAD_REQUEST).entity(resultMap).build();
306
307             }
308             return response.status(Status.OK).entity(resultMap).build();
309         }
310
311         pQuery.appendQueryString(
312                         "select uuid from admin.keyspace_master where application_name = ? allow filtering");
313         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
314         ResultSet rs = MusicCore.get(pQuery);
315         List<Row> rows = rs.all();
316         String uuid = null;
317         if (rows.isEmpty()) {
318             resultMap.put("Exception",
319                             "Application not found. Please make sure Application exists.");
320             logger.error(EELFLoggerDelegate.errorLogger, "Application not found. Please make sure Application exists.", AppMessages.INCORRECTDATA,
321                             ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
322             return response.status(Status.BAD_REQUEST).entity(resultMap).build();
323         } else if (rows.size() == 1) {
324             uuid = rows.get(0).getUUID("uuid").toString();
325             pQuery = new PreparedQueryObject();
326             pQuery.appendQueryString(
327                             "SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?");
328             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
329                             UUID.fromString(uuid)));
330             Row row = MusicCore.get(pQuery).one();
331             String ks = row.getString("keyspace_name");
332             if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
333                 PreparedQueryObject queryObject = new PreparedQueryObject();
334                 queryObject.appendQueryString("DROP KEYSPACE " + ks + ";");
335                 MusicCore.nonKeyRelatedPut(queryObject, consistency);
336             }
337
338             pQuery = new PreparedQueryObject();
339             pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?");
340             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
341                             UUID.fromString(uuid)));
342             MusicCore.eventualPut(pQuery);
343             resultMap.put("Success", "Your application " + appName + " has been deleted.");
344             return response.status(Status.OK).entity(resultMap).build();
345         } else {
346             resultMap.put("Failure",
347                             "More than one Aid exists for this application, so please provide Aid.");
348             logger.error(EELFLoggerDelegate.errorLogger, "More than one Aid exists for this application, so please provide Aid.", AppMessages.MULTIPLERECORDS,
349                             ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
350             return response.status(Status.BAD_REQUEST).entity(resultMap).build();
351         }
352     }
353
354
355     @PUT
356     @Path("/onboardAppWithMusic")
357     @ApiOperation(value = "Update Onboard application", response = String.class)
358     @Consumes(MediaType.APPLICATION_JSON)
359     @Produces(MediaType.APPLICATION_JSON)
360     public Response updateOnboardApp(JsonOnboard jsonObj,
361             @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception {
362         ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
363         if (!authenticator.authenticateAdmin(authorization)) {
364             logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
365                     ErrorTypes.AUTHENTICATIONERROR);
366             return response.status(Status.UNAUTHORIZED)
367                     .entity(new JsonResponse(ResultType.FAILURE)
368                             .setError("Unauthorized: Please check admin username,password and try again").toMap())
369                     .build();
370         }
371         
372         Map<String, Object> resultMap = new HashMap<>();
373         String aid = jsonObj.getAid();
374         String appName = jsonObj.getAppname();
375         String userId = jsonObj.getUserId();
376         String cassandraKeyspace=jsonObj.getKeyspace();
377         String consistency = "eventual";
378         PreparedQueryObject pQuery;
379         
380         if (aid == null) {
381             resultMap.put("Exception", "Please make sure Aid is present");
382             logger.error(EELFLoggerDelegate.errorLogger, "Please make sure Aid is present", AppMessages.MISSINGDATA,
383                             ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
384             return response.status(Status.BAD_REQUEST).entity(resultMap).build();
385         }
386
387         if (appName == null || userId == null || cassandraKeyspace == null) {
388             resultMap.put("Exception",
389                             "No parameters found to update. Please update atleast one parameter.");
390             logger.error(EELFLoggerDelegate.errorLogger, "No parameters found to update. Please update atleast one parameter.", AppMessages.MISSINGDATA,
391                             ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
392             return response.status(Status.BAD_REQUEST).entity(resultMap).build();
393         }
394
395         if (appName != null) {
396             pQuery = new PreparedQueryObject();
397             pQuery.appendQueryString(
398                             "select uuid from admin.keyspace_master where application_name = ? allow filtering");
399             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
400             ResultSet rs = MusicCore.get(pQuery);
401             if (rs.all().isEmpty()) {
402                 resultMap.put("Exception", "Application " + appName
403                                 + " not found. Please contact admin.");
404                 logger.error(EELFLoggerDelegate.errorLogger, "Application " + appName+"not found. Please contact admin.", AppMessages.ALREADYEXIST,
405                                 ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
406                 return response.status(Status.BAD_REQUEST).entity(resultMap).build();
407             }
408         }
409
410         pQuery = new PreparedQueryObject();
411         StringBuilder preCql = new StringBuilder("UPDATE admin.keyspace_master SET ");
412         if (appName != null)
413             preCql.append(" application_name = ?,");
414         if (userId != null)
415             preCql.append(" username = ?,");
416         if (cassandraKeyspace != null)
417             preCql.append(" keyspace_name = ?,");
418         preCql.deleteCharAt(preCql.length() - 1);
419         preCql.append(" WHERE uuid = ? IF EXISTS");
420         pQuery.appendQueryString(preCql.toString());
421         if (appName != null)
422             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
423         if (userId != null)
424             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
425         if (cassandraKeyspace != null)
426             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), cassandraKeyspace));
427
428         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid)));
429         ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
430
431         if (result == ResultType.SUCCESS) {
432             resultMap.put("Success", "Your application has been updated successfully");
433         } else {
434             resultMap.put("Exception",
435                             "Oops. Something went wrong. Please make sure Aid is correct and application is onboarded");
436             logger.error(EELFLoggerDelegate.errorLogger, "Oops. Something went wrong. Please make sure Aid is correct and application is onboarded", AppMessages.INCORRECTDATA,
437                             ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
438             return response.status(Status.BAD_REQUEST).entity(resultMap).build();
439         }
440
441         return response.status(Status.OK).entity(resultMap).build();
442     }
443
444     
445     
446   //Dashboard related calls
447   //TODO Make return object Response.
448     
449     @GET
450     @Path("/getall")
451     @Produces(MediaType.APPLICATION_JSON)
452     @Consumes(MediaType.APPLICATION_JSON)
453     public MusicResponse getall(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws MusicServiceException{
454         MusicResponse response  = new MusicResponse();
455         if (!authenticator.authenticateAdmin(authorization)) {
456             logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
457                     ErrorTypes.AUTHENTICATIONERROR);
458             response.setResposne("fail", "Auth failed for admin");
459             return response;
460         }
461         
462         PreparedQueryObject queryObject = new PreparedQueryObject();
463         queryObject.appendQueryString("SELECT *  FROM " + "admin" + "." + "keyspace_master" + ";");
464         try {
465         ResultSet results = MusicCore.get(queryObject);
466         for(Row row : results) {
467             Application app = new Application();
468             app.setApplication_name(row.getString("application_name"));
469             app.setIs_aaf(row.getBool("is_aaf"));
470             app.setIs_api(row.getBool("is_api"));
471             app.setUsername(row.getString("username"));
472             app.setKeyspace_name(row.getString("keyspace_name"));
473             app.setUuid(row.getUUID("uuid").toString());
474             response.addAppToList(app);
475         }
476         }catch(Exception ex) {
477                 response.setResposne("fail", ex.getMessage());
478         }
479         return response;
480         
481     }
482     
483     
484     @DELETE
485     @Path("/delete")
486     @Produces(MediaType.APPLICATION_JSON)
487     @Consumes(MediaType.APPLICATION_JSON)
488     public MusicResponse delete(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
489             @ApiParam(value = "uuid", required = true) @HeaderParam("uuid") String uuid) throws Exception {
490         MusicResponse response = new MusicResponse();
491         if (!authenticator.authenticateAdmin(authorization)) {
492             logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
493                     ErrorTypes.AUTHENTICATIONERROR);
494             response.setResposne("fail", "Auth failed for admin");
495             return response;
496         }
497         PreparedQueryObject queryObject = new PreparedQueryObject();
498         queryObject.appendQueryString("delete from admin.keyspace_master where uuid=?");
499         queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),uuid));
500         ResultType result;
501         try {
502             result = MusicCore.nonKeyRelatedPut(queryObject, "eventual");
503             response.setResposne("success", "Application deleted successfully. Please contact ops team to delete keyspace");
504         }catch(Exception ex) {
505             logger.error(EELFLoggerDelegate.errorLogger, ex);
506             response.setResposne("fail", ex.getMessage());
507             return response;
508         }
509         return response;
510     }
511     
512     @POST
513     @Path("/onboard")
514     @ApiOperation(value = "Onboard application", response = String.class)
515     @Consumes(MediaType.APPLICATION_JSON)
516     @Produces(MediaType.APPLICATION_JSON)
517     public MusicResponse onboard(JsonOnboard jsonObj,
518             @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception {
519         logger.info(EELFLoggerDelegate.errorLogger, "oboarding app");
520         MusicResponse response = new MusicResponse();
521         if (!authenticator.authenticateAdmin(authorization)) {
522             logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
523                     ErrorTypes.AUTHENTICATIONERROR);
524             response.setResposne("fail", "auth error");
525         }
526         PreparedQueryObject pQurey = new PreparedQueryObject();
527         pQurey.appendQueryString("Describe keyspace + ?");
528         pQurey.addValue(MusicUtil.convertToActualDataType(DataType.text(),jsonObj.getKeyspace()));
529         KeyspaceMetadata keyspaceInfo = null;
530         //authenticator.checkOnbaordUserAccess(jsonObj.getUserId(), jsonObj.getAppname());
531         try {
532             keyspaceInfo = MusicDataStoreHandle.returnkeyspaceMetadata(jsonObj.getKeyspace());
533         }catch (Exception e) {
534                         logger.info(EELFLoggerDelegate.applicationLogger,"Application onbaord failed for "+ jsonObj.getKeyspace());
535                         
536                 }
537         if(keyspaceInfo == null) {
538             logger.info(EELFLoggerDelegate.applicationLogger,"Keyspace does not exist, contact music support to create a keyspace and onbaord again");
539             response.setResposne("fail", "Keyspace does not exist, contact music support to create a keyspace and onboard again");
540             return response;
541         }
542         Response result = null;
543         try {
544             result = onboardAppWithMusic(jsonObj, authorization);
545             if(result.getStatus()!= 200) {
546                 response.setResposne("fail", result.getEntity().toString());
547             }else {
548                 response.setResposne("success", "Onboard Success");
549             }
550         }catch(Exception ex) {
551             response.setResposne("fail", ex.getMessage());
552             return response;
553     
554         }
555         return response;
556     }
557     
558     @POST
559     @Path("/disable")
560     @ApiOperation(value = "Onboard application", response = String.class)
561     @Consumes(MediaType.APPLICATION_JSON)
562     @Produces(MediaType.APPLICATION_JSON)
563     public MusicResponse disableApplicationAccess(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
564             @ApiParam(value = "uuid", required = true) @HeaderParam("uuid") String uuid) throws Exception {
565         logger.info(EELFLoggerDelegate.errorLogger, "oboarding app");
566         MusicResponse response = new MusicResponse();
567         if (!authenticator.authenticateAdmin(authorization)) {
568             logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
569                     ErrorTypes.AUTHENTICATIONERROR);
570           response.setResposne("fail", "Authorization failed for music admin");
571         }
572         PreparedQueryObject queryObject = new PreparedQueryObject();
573         queryObject.appendQueryString("SELECT * from admin.keyspace_master where uuid = ?");
574         queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
575         Row row = MusicDataStoreHandle.getDSHandle().executeGet(queryObject, "eventual").one();
576         boolean toggleAccess = row.getBool("is_api");
577         queryObject = null;
578         queryObject = new PreparedQueryObject();
579         queryObject.appendQueryString("UPDATE admin.keyspace_master SET is_api = ? WHERE uuid = ?");
580         queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), !toggleAccess));
581         queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
582         try {
583                 MusicDataStoreHandle.getDSHandle().executePut(queryObject, "eventual");
584                 response.setResposne("success","Access toggle success");
585         }catch(Exception ex) {
586                 response.setResposne("fail", ex.getMessage());
587         }
588                         
589         return response;
590     }
591     
592     @POST
593     @Path("/editApplication")
594     @ApiOperation(value = "Onboard application", response = String.class)
595     @Consumes(MediaType.APPLICATION_JSON)
596     @Produces(MediaType.APPLICATION_JSON)
597     public MusicResponse editApplication(JsonOnboard jsonObj,
598             @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception {
599         logger.info(EELFLoggerDelegate.errorLogger, "oboarding app");
600        MusicResponse response = new MusicResponse();
601         if (!authenticator.authenticateAdmin(authorization)) {
602             logger.info(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL,
603                     ErrorTypes.AUTHENTICATIONERROR);
604           response.setResposne("fail", "auth error");
605         }
606         KeyspaceMetadata keyspaceInfo = null;
607         try {
608                 keyspaceInfo = MusicDataStoreHandle.returnkeyspaceMetadata(jsonObj.getKeyspace());
609         }catch (Exception e) {
610                         logger.info(EELFLoggerDelegate.applicationLogger,"Application Update failed for "+ jsonObj.getKeyspace());
611                         
612                 }
613         if(keyspaceInfo == null) {
614             logger.info(EELFLoggerDelegate.applicationLogger,"Keyspace does not exist, contact music support to create a keyspace and onbaord again");
615             response.setResposne("fail", "Keyspace does not exist, contact music support to create a keyspace and update again");
616             return response;
617          }
618         
619         try {
620         Response res = updateOnboardApp(jsonObj, authorization);
621         if(res.getStatus() != 200) {
622                 response.setResposne("fail", res.getEntity().toString());
623         }else
624                 response.setResposne("success", "Update success");
625         }catch(Exception ex){
626                 logger.info(EELFLoggerDelegate.errorLogger,"Exception while updating application");
627                 logger.info(EELFLoggerDelegate.errorLogger,ex.getMessage());
628                 response.setResposne("fail", ex.getMessage());
629                 
630         }
631      return response;
632     }
633     
634     
635 }