Add voting app example
[music.git] / src / main / java / org / onap / music / conductor / conditionals / RestMusicConditonalAPI.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.conductor.conditionals;
23
24 import java.util.HashMap;
25 import java.util.LinkedHashMap;
26 import java.util.Map;
27
28 import javax.ws.rs.Consumes;
29 import javax.ws.rs.HeaderParam;
30 import javax.ws.rs.POST;
31 import javax.ws.rs.PUT;
32 import javax.ws.rs.Path;
33 import javax.ws.rs.PathParam;
34 import javax.ws.rs.Produces;
35 import javax.ws.rs.core.MediaType;
36 import javax.ws.rs.core.Response;
37 import javax.ws.rs.core.Response.ResponseBuilder;
38 import javax.ws.rs.core.Response.Status;
39
40 import org.codehaus.jettison.json.JSONObject;
41 import org.onap.music.datastore.PreparedQueryObject;
42 import org.onap.music.eelf.logging.EELFLoggerDelegate;
43 import org.onap.music.eelf.logging.format.AppMessages;
44 import org.onap.music.eelf.logging.format.ErrorSeverity;
45 import org.onap.music.eelf.logging.format.ErrorTypes;
46 import org.onap.music.main.MusicCore;
47 import org.onap.music.main.MusicUtil;
48 import org.onap.music.main.ResultType;
49 import org.onap.music.main.ReturnType;
50 import org.onap.music.response.jsonobjects.JsonResponse;
51 import org.onap.music.rest.RestMusicAdminAPI;
52
53 import com.datastax.driver.core.DataType;
54 import com.datastax.driver.core.TableMetadata;
55
56 import io.swagger.annotations.Api;
57 import io.swagger.annotations.ApiParam;
58
59 @Path("/v2/conditional")
60 @Api(value = "Conditional Api", hidden = true)
61 public class RestMusicConditonalAPI {
62         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class);
63         private static final String XMINORVERSION = "X-minorVersion";
64         private static final String XPATCHVERSION = "X-patchVersion";
65         private static final String NS = "ns";
66         private static final String USERID = "userId";
67         private static final String PASSWORD = "password";
68         private static final String VERSION = "v2";
69
70         @POST
71         @Path("/insert/keyspaces/{keyspace}/tables/{tablename}")
72         @Consumes(MediaType.APPLICATION_JSON)
73         @Produces(MediaType.APPLICATION_JSON)
74         public Response insertConditional(
75                         @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
76                         @ApiParam(value = "Minor Version", required = false) @HeaderParam(XMINORVERSION) String minorVersion,
77                         @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
78                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
79                         @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns,
80                         @ApiParam(value = "userId", required = true) @HeaderParam(USERID) String userId,
81                         @ApiParam(value = "Password", required = true) @HeaderParam(PASSWORD) String password,
82                         @ApiParam(value = "Major Version", required = true) @PathParam("keyspace") String keyspace,
83                         @ApiParam(value = "Major Version", required = true) @PathParam("tablename") String tablename,
84                         JsonConditional jsonObj) throws Exception {
85                 ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
86                 String primaryKey = jsonObj.getPrimaryKey();
87                 String primaryKeyValue = jsonObj.getPrimaryKeyValue();
88                 String casscadeColumnName = jsonObj.getCasscadeColumnName();
89                 Map<String, Object> tableValues = jsonObj.getTableValues();
90                 Map<String, Object> casscadeColumnData = jsonObj.getCasscadeColumnData();
91                 Map<String, Map<String, String>> conditions = jsonObj.getConditions();
92
93                 if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null || tableValues.isEmpty()
94                                 || casscadeColumnData.isEmpty() || conditions.isEmpty()) {
95                         logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
96                                         ErrorTypes.AUTHENTICATIONERROR);
97                         return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE)
98                                         .setError(String.valueOf("One or more input values missing")).toMap()).build();
99
100                 }
101
102                 Map<String, Object> authMap = null;
103                 try {
104                         authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "insertIntoTable");
105                 } catch (Exception e) {
106                         logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
107                                         ErrorTypes.AUTHENTICATIONERROR);
108                         return response.status(Status.UNAUTHORIZED)
109                                         .entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
110                 }
111                 if (authMap.containsKey("aid"))
112                         authMap.remove("aid");
113                 if (!authMap.isEmpty()) {
114                         logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
115                                         ErrorTypes.AUTHENTICATIONERROR);
116                         return response.status(Status.UNAUTHORIZED).entity(
117                                         new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap())
118                                         .build();
119                 }
120
121                 Map<String, Object> valuesMap = new LinkedHashMap<>();
122                 for (Map.Entry<String, Object> entry : tableValues.entrySet()) {
123                         valuesMap.put(entry.getKey(), entry.getValue());
124                 }
125
126                 Map<String, String> status = new HashMap<>();
127                 status.put("exists", conditions.get("exists").get("status").toString());
128                 status.put("nonexists", conditions.get("nonexists").get("status").toString());
129                 ReturnType out = null;
130
131                 out = MusicContional.conditionalInsert(keyspace, tablename, casscadeColumnName, casscadeColumnData,
132                                 primaryKeyValue, valuesMap, status);
133                 return response.status(Status.OK).entity(new JsonResponse(out.getResult()).setMessage(out.getMessage()).toMap())
134                                 .build();
135
136         }
137
138         @SuppressWarnings("unchecked")
139         @PUT
140         @Path("/update/keyspaces/{keyspace}/tables/{tablename}")
141         @Consumes(MediaType.APPLICATION_JSON)
142         @Produces(MediaType.APPLICATION_JSON)
143         public Response updateConditional(
144                         @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
145                         @ApiParam(value = "Minor Version", required = false) @HeaderParam(XMINORVERSION) String minorVersion,
146                         @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
147                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
148                         @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns,
149                         @ApiParam(value = "userId", required = true) @HeaderParam(USERID) String userId,
150                         @ApiParam(value = "Password", required = true) @HeaderParam(PASSWORD) String password,
151                         @ApiParam(value = "Major Version", required = true) @PathParam("keyspace") String keyspace,
152                         @ApiParam(value = "Major Version", required = true) @PathParam("tablename") String tablename,
153                         JsonConditional upObj) throws Exception {
154                 ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
155
156                 String primaryKey = upObj.getPrimaryKey();
157                 String primaryKeyValue = upObj.getPrimaryKeyValue();
158                 String casscadeColumnName = upObj.getCasscadeColumnName();
159                 Map<String, Object> casscadeColumnData = upObj.getCasscadeColumnData();
160                 Map<String, Object> tableValues = upObj.getTableValues();
161
162                 if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null
163                                 || casscadeColumnData.isEmpty()) {
164                         logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
165                                         ErrorTypes.AUTHENTICATIONERROR);
166                         return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE)
167                                         .setError(String.valueOf("One or more input values missing")).toMap()).build();
168
169                 }
170
171                 Map<String, Object> authMap = null;
172                 try {
173                         authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "updateTable");
174                 } catch (Exception e) {
175                         logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
176                                         ErrorTypes.AUTHENTICATIONERROR);
177                         return response.status(Status.UNAUTHORIZED)
178                                         .entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
179                 }
180                 if (authMap.containsKey("aid"))
181                         authMap.remove("aid");
182                 if (!authMap.isEmpty()) {
183                         logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
184                                         ErrorTypes.AUTHENTICATIONERROR);
185                         return response.status(Status.UNAUTHORIZED).entity(
186                                         new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap())
187                                         .build();
188                 }
189
190                 String planId = casscadeColumnData.get("key").toString();
191                 Map<String,String> casscadeColumnValueMap = (Map<String, String>) casscadeColumnData.get("value");
192                 TableMetadata tableInfo = null;
193                 tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename);
194                 DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType();
195                 String primaryId = tableInfo.getPrimaryKey().get(0).getName();
196                 
197                 PreparedQueryObject upsert = MusicContional.extractQuery(tableValues, tableInfo, tablename, keyspace, primaryKey, primaryKeyValue, null, null);
198                 
199                 PreparedQueryObject select = new PreparedQueryObject();
200                 select.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " where " + primaryId + " = ?");
201                 select.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKeyValue));
202                 
203                 Map<String,PreparedQueryObject> queryBank = new HashMap<>();
204                 //queryBank.put(MusicUtil.UPDATE, update);
205                 queryBank.put(MusicUtil.UPSERT, upsert);
206                 queryBank.put(MusicUtil.SELECT, select);
207                 ReturnType result = MusicContional.update(queryBank, keyspace, tablename, primaryKey,primaryKeyValue,planId,casscadeColumnName,casscadeColumnValueMap);
208                 if (result.getResult() == ResultType.SUCCESS) {
209                         return response.status(Status.OK)
210                                         .entity(new JsonResponse(result.getResult()).setMessage(result.getMessage()).toMap()).build();
211
212                 }
213                 return response.status(Status.BAD_REQUEST)
214                                 .entity(new JsonResponse(result.getResult()).setMessage(result.getMessage()).toMap()).build();
215
216         }
217
218 }