Initial code Import.
[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 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.UUID;
29 import javax.servlet.http.HttpServletResponse;
30 import javax.ws.rs.Consumes;
31 import javax.ws.rs.DELETE;
32 import javax.ws.rs.GET;
33 import javax.ws.rs.HeaderParam;
34 import javax.ws.rs.POST;
35 import javax.ws.rs.PUT;
36 import javax.ws.rs.Path;
37 import javax.ws.rs.Produces;
38 import javax.ws.rs.core.Context;
39 import javax.ws.rs.core.MediaType;
40 import org.onap.music.datastore.PreparedQueryObject;
41 import org.onap.music.datastore.jsonobjects.JsonOnboard;
42 import org.onap.music.main.CachingUtil;
43 import org.onap.music.main.MusicCore;
44 import org.onap.music.main.MusicUtil;
45 import com.att.eelf.configuration.EELFLogger;
46 import com.att.eelf.configuration.EELFManager;
47 import com.datastax.driver.core.DataType;
48 import com.datastax.driver.core.ResultSet;
49 import com.datastax.driver.core.Row;
50 import io.swagger.annotations.Api;
51 import io.swagger.annotations.ApiOperation;
52 import io.swagger.annotations.ApiParam;
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 EELFLogger logger = EELFManager.getInstance().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             resultMap.put("Exception",
79                             "Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing.");
80             return resultMap;
81         }
82
83         PreparedQueryObject pQuery = new PreparedQueryObject();
84         pQuery.appendQueryString(
85                         "select uuid from admin.keyspace_master where application_name = ? allow filtering");
86         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
87         ResultSet rs = MusicCore.get(pQuery);
88         if (!rs.all().isEmpty()) {
89             resultMap.put("Exception", "Your application " + appName
90                             + " has already been onboarded. Please contact admin.");
91             return resultMap;
92         }
93
94         pQuery = new PreparedQueryObject();
95         String uuid = CachingUtil.generateUUID();
96         pQuery.appendQueryString(
97                         "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
98                                         + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)");
99         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
100         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),
101                         MusicUtil.DEFAULTKEYSPACENAME));
102         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
103         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
104         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), password));
105         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
106         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
107
108         String returnStr = MusicCore.eventualPut(pQuery).toString();
109         if (returnStr.contains("Failure")) {
110             resultMap.put("Exception",
111                             "Oops. Something wrong with onboarding process. Please retry later or contact admin.");
112             return resultMap;
113         }
114         CachingUtil.updateisAAFCache(appName, isAAF);
115         resultMap.put("Success", "Your application " + appName + " has been onboarded with MUSIC.");
116         resultMap.put("Generated AID", uuid);
117         return resultMap;
118     }
119
120
121     /*
122      * API to onboard an application with MUSIC. This is the mandatory first step.
123      * 
124      */
125     @GET
126     @Path("/onboardAppWithMusic")
127     @ApiOperation(value = "Onboard application", response = String.class)
128     @Consumes(MediaType.APPLICATION_JSON)
129     @Produces(MediaType.APPLICATION_JSON)
130     public Map<String, Object> getOnboardedInfo(
131                     @ApiParam(value = "AID", required = true) @HeaderParam("aid") String uuid,
132                     @ApiParam(value = "Application namespace",
133                                     required = true) @HeaderParam("ns") String appName,
134                     @Context HttpServletResponse response) throws Exception {
135         Map<String, Object> resultMap = new HashMap<>();
136
137         response.addHeader("X-latestVersion", MusicUtil.getVersion());
138         if (appName == null && uuid == null) {
139             resultMap.put("Exception",
140                             "Please check the request parameters. Some of the required values appName(ns), aid are missing.");
141             return resultMap;
142         }
143
144         PreparedQueryObject pQuery = new PreparedQueryObject();
145
146         String cql = "select uuid, keyspace_name from admin.keyspace_master where ";
147         if (appName != null)
148             cql = cql + "application_name = ?";
149         else if (uuid != null)
150             cql = cql + "uuid = ?";
151         cql = cql + " allow filtering";
152         System.out.println("Get OnboardingInfo CQL: " + cql);
153         pQuery.appendQueryString(cql);
154         if (appName != null)
155             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
156         else if (uuid != null)
157             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
158         ResultSet rs = MusicCore.get(pQuery);
159         Iterator<Row> it = rs.iterator();
160         while (it.hasNext()) {
161             Row row = (Row) it.next();
162             resultMap.put(row.getString("keyspace_name"), row.getUUID("uuid"));
163         }
164         if (resultMap.isEmpty())
165             resultMap.put("ERROR", "Application is not onboarded. Please contact admin.");
166         return resultMap;
167     }
168
169
170     @DELETE
171     @Path("/onboardAppWithMusic")
172     @ApiOperation(value = "Delete Onboard application", response = String.class)
173     @Consumes(MediaType.APPLICATION_JSON)
174     @Produces(MediaType.APPLICATION_JSON)
175     public Map<String, Object> deleteOnboardApp(JsonOnboard jsonObj,
176                     @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
177                     @Context HttpServletResponse response) throws Exception {
178         Map<String, Object> resultMap = new HashMap<>();
179         response.addHeader("X-latestVersion", MusicUtil.getVersion());
180         String appName = jsonObj.getAppname();
181         PreparedQueryObject pQuery = new PreparedQueryObject();
182         long count = 0;
183         if (appName == null && aid == null) {
184             resultMap.put("Exception", "Please make sure either appName(ns) or Aid is present");
185             return resultMap;
186         }
187         if (aid != null) {
188             pQuery.appendQueryString(
189                             "select count(*) as count from admin.keyspace_master where uuid = ?");
190             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
191                             UUID.fromString(aid)));
192             Row row = MusicCore.get(pQuery).one();
193             if (row != null) {
194                 count = row.getLong(0);
195             }
196
197             if (count == 0) {
198                 resultMap.put("Failure", "Please verify your AID.");
199                 return resultMap;
200             } else {
201                 pQuery = new PreparedQueryObject();
202                 pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?");
203                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
204                                 UUID.fromString(aid)));
205                 String result = MusicCore.eventualPut(pQuery).toString();
206                 if (result.toLowerCase().contains("success")) {
207                     resultMap.put("Success", "Your application has been deleted.");
208                     return resultMap;
209                 } else {
210                     resultMap.put("Failure", "Please verify your AID.");
211                     return resultMap;
212                 }
213             }
214
215         }
216         pQuery.appendQueryString(
217                         "select uuid from admin.keyspace_master where application_name = ? allow filtering");
218         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
219         ResultSet rs = MusicCore.get(pQuery);
220         List<Row> rows = rs.all();
221         String uuid = null;
222         if (rows.size() == 0) {
223             resultMap.put("Exception",
224                             "Application not found. Please make sure Application exists.");
225             return resultMap;
226         } else if (rows.size() == 1) {
227             uuid = rows.get(0).getUUID("uuid").toString();
228             pQuery = new PreparedQueryObject();
229             pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?");
230             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
231                             UUID.fromString(uuid)));
232             MusicCore.eventualPut(pQuery);
233             resultMap.put("Success", "Your application " + appName + " has been deleted.");
234             return resultMap;
235         } else {
236             resultMap.put("Failure", "Please provide UUID for the application.");
237         }
238
239         return resultMap;
240     }
241
242
243     @PUT
244     @Path("/onboardAppWithMusic")
245     @ApiOperation(value = "Update Onboard application", response = String.class)
246     @Consumes(MediaType.APPLICATION_JSON)
247     @Produces(MediaType.APPLICATION_JSON)
248     public Map<String, Object> updateOnboardApp(JsonOnboard jsonObj,
249                     @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
250                     @Context HttpServletResponse response) throws Exception {
251         Map<String, Object> resultMap = new HashMap<>();
252         response.addHeader("X-latestVersion", MusicUtil.getVersion());
253         String appName = jsonObj.getAppname();
254         String userId = jsonObj.getUserId();
255         String isAAF = jsonObj.getIsAAF();
256         String password = jsonObj.getPassword();
257         String consistency = "eventual";
258         PreparedQueryObject pQuery = new PreparedQueryObject();
259
260         if (aid == null) {
261             resultMap.put("Exception", "Please make sure Aid is present");
262             return resultMap;
263         }
264
265         if (appName == null && userId == null && password == null && isAAF == null) {
266             resultMap.put("Exception",
267                             "No parameters found to update. Please update atleast one parameter.");
268             return resultMap;
269         }
270
271         StringBuilder preCql = new StringBuilder("UPDATE admin.keyspace_master SET ");
272         if (appName != null)
273             preCql.append(" application_name = ?,");
274         if (userId != null)
275             preCql.append(" username = ?,");
276         if (password != null)
277             preCql.append(" password = ?,");
278         if (isAAF != null)
279             preCql.append(" is_aaf = ?,");
280         preCql.deleteCharAt(preCql.length() - 1);
281         preCql.append(" WHERE uuid = ?");
282         pQuery.appendQueryString(preCql.toString());
283         if (appName != null)
284             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
285         if (userId != null)
286             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
287         if (password != null)
288             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), password));
289         if (isAAF != null)
290             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
291
292
293         pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid)));
294         Boolean result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
295
296         if (result) {
297             resultMap.put("Success", "Your application has been updated successfully");
298         } else {
299             resultMap.put("Exception",
300                             "Oops. Spomething went wrong. Please make sure Aid is correct and application is onboarded");
301         }
302
303         return resultMap;
304     }
305 }