2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (c) 2017 AT&T Intellectual Property
6 * ===================================================================
7 * Modifications Copyright (c) 2018 IBM
8 * ===================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ============LICENSE_END=============================================
22 * ====================================================================
25 package org.onap.music.conductor.conditionals;
27 import java.util.HashMap;
28 import java.util.LinkedHashMap;
31 import javax.ws.rs.Consumes;
32 import javax.ws.rs.HeaderParam;
33 import javax.ws.rs.POST;
34 import javax.ws.rs.PUT;
35 import javax.ws.rs.Path;
36 import javax.ws.rs.PathParam;
37 import javax.ws.rs.Produces;
38 import javax.ws.rs.core.MediaType;
39 import javax.ws.rs.core.Response;
40 import javax.ws.rs.core.Response.ResponseBuilder;
41 import javax.ws.rs.core.Response.Status;
43 import org.codehaus.jettison.json.JSONObject;
44 import org.onap.music.datastore.MusicDataStoreHandle;
45 import org.onap.music.datastore.PreparedQueryObject;
46 import org.onap.music.eelf.logging.EELFLoggerDelegate;
47 import org.onap.music.eelf.logging.format.AppMessages;
48 import org.onap.music.eelf.logging.format.ErrorSeverity;
49 import org.onap.music.eelf.logging.format.ErrorTypes;
50 import org.onap.music.main.MusicUtil;
51 import org.onap.music.main.ResultType;
52 import org.onap.music.main.ReturnType;
53 import org.onap.music.response.jsonobjects.JsonResponse;
54 import org.onap.music.rest.RestMusicAdminAPI;
55 import org.onap.music.authentication.MusicAuthentication;
56 import org.onap.music.conductor.*;
58 import com.datastax.driver.core.DataType;
59 import com.datastax.driver.core.TableMetadata;
61 import io.swagger.annotations.Api;
62 import io.swagger.annotations.ApiParam;
64 @Path("/v2/conditional")
65 @Api(value = "Conditional Api", hidden = true)
66 public class RestMusicConditionalAPI {
67 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class);
68 private static final String XMINORVERSION = "X-minorVersion";
69 private static final String XPATCHVERSION = "X-patchVersion";
70 private static final String NS = "ns";
71 private static final String VERSION = "v2";
74 @Path("/insert/keyspaces/{keyspace}/tables/{tablename}")
75 @Consumes(MediaType.APPLICATION_JSON)
76 @Produces(MediaType.APPLICATION_JSON)
77 public Response insertConditional(
78 @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
79 @ApiParam(value = "Minor Version", required = false) @HeaderParam(XMINORVERSION) String minorVersion,
80 @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
81 @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
82 @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns,
83 @ApiParam(value = "Authorization", required = true) @HeaderParam("Authorization") String authorization,
84 @ApiParam(value = "Keyspace Name", required = true) @PathParam("keyspace") String keyspace,
85 @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename,
86 JsonConditional jsonObj) throws Exception {
87 ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
88 String primaryKey = jsonObj.getPrimaryKey();
89 String primaryKeyValue = jsonObj.getPrimaryKeyValue();
90 String casscadeColumnName = jsonObj.getCasscadeColumnName();
91 Map<String, Object> tableValues = jsonObj.getTableValues();
92 Map<String, Object> casscadeColumnData = jsonObj.getCasscadeColumnData();
93 Map<String, Map<String, String>> conditions = jsonObj.getConditions();
95 if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null || tableValues.isEmpty()
96 || casscadeColumnData.isEmpty() || conditions.isEmpty()) {
97 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
98 ErrorTypes.AUTHENTICATIONERROR);
99 return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE)
100 .setError(String.valueOf("One or more input values missing")).toMap()).build();
103 Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
104 String userId = userCredentials.get(MusicUtil.USERID);
105 String password = userCredentials.get(MusicUtil.PASSWORD);
107 Map<String, Object> authMap = null;
109 authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace, aid, "insertIntoTable");
110 } catch (Exception e) {
111 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
112 ErrorTypes.AUTHENTICATIONERROR);
113 return response.status(Status.UNAUTHORIZED)
114 .entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
116 if (authMap.containsKey("aid"))
117 authMap.remove("aid");
118 if (!authMap.isEmpty()) {
119 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
120 ErrorTypes.AUTHENTICATIONERROR);
121 return response.status(Status.UNAUTHORIZED).entity(
122 new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap())
126 Map<String, Object> valuesMap = new LinkedHashMap<>();
127 for (Map.Entry<String, Object> entry : tableValues.entrySet()) {
128 valuesMap.put(entry.getKey(), entry.getValue());
131 Map<String, String> status = new HashMap<>();
132 status.put("exists", conditions.get("exists").get("status"));
133 status.put("nonexists", conditions.get("nonexists").get("status"));
134 ReturnType out = null;
136 out = MusicConditional.conditionalInsert(keyspace, tablename, casscadeColumnName, casscadeColumnData,
137 primaryKeyValue, valuesMap, status);
138 return response.status(Status.OK).entity(new JsonResponse(out.getResult()).setMessage(out.getMessage()).toMap())
143 @SuppressWarnings("unchecked")
145 @Path("/update/keyspaces/{keyspace}/tables/{tablename}")
146 @Consumes(MediaType.APPLICATION_JSON)
147 @Produces(MediaType.APPLICATION_JSON)
148 public Response updateConditional(
149 @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
150 @ApiParam(value = "Minor Version", required = false) @HeaderParam(XMINORVERSION) String minorVersion,
151 @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
152 @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
153 @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns,
154 @ApiParam(value = "Authorization", required = true) @HeaderParam("Authorization") String authorization,
155 @ApiParam(value = "Major Version", required = true) @PathParam("keyspace") String keyspace,
156 @ApiParam(value = "Major Version", required = true) @PathParam("tablename") String tablename,
157 JsonConditional upObj) throws Exception {
158 ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
160 String primaryKey = upObj.getPrimaryKey();
161 String primaryKeyValue = upObj.getPrimaryKeyValue();
162 String casscadeColumnName = upObj.getCasscadeColumnName();
163 Map<String, Object> casscadeColumnData = upObj.getCasscadeColumnData();
164 Map<String, Object> tableValues = upObj.getTableValues();
166 if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null
167 || casscadeColumnData.isEmpty()) {
168 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
169 ErrorTypes.AUTHENTICATIONERROR);
170 return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE)
171 .setError(String.valueOf("One or more input values missing")).toMap()).build();
174 Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
175 String userId = userCredentials.get(MusicUtil.USERID);
176 String password = userCredentials.get(MusicUtil.PASSWORD);
178 Map<String, Object> authMap = null;
180 authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace, aid, "updateTable");
181 } catch (Exception e) {
182 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
183 ErrorTypes.AUTHENTICATIONERROR);
184 return response.status(Status.UNAUTHORIZED)
185 .entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
187 if (authMap.containsKey("aid"))
188 authMap.remove("aid");
189 if (!authMap.isEmpty()) {
190 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
191 ErrorTypes.AUTHENTICATIONERROR);
192 return response.status(Status.UNAUTHORIZED).entity(
193 new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap())
197 String planId = casscadeColumnData.get("key").toString();
198 Map<String,String> casscadeColumnValueMap = (Map<String, String>) casscadeColumnData.get("value");
199 TableMetadata tableInfo = null;
200 tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename);
201 DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType();
202 String primaryId = tableInfo.getPrimaryKey().get(0).getName();
204 PreparedQueryObject select = new PreparedQueryObject();
205 select.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " where " + primaryId + " = ?");
206 select.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKeyValue));
208 PreparedQueryObject upsert = MusicConditional.extractQuery(tableValues, tableInfo, tablename, keyspace, primaryKey, primaryKeyValue, null, null);
209 Map<String,PreparedQueryObject> queryBank = new HashMap<>();
210 queryBank.put(MusicUtil.SELECT, select);
211 queryBank.put(MusicUtil.UPSERT, upsert);
212 ReturnType result = MusicConditional.update(queryBank, keyspace, tablename, primaryKey,primaryKeyValue,planId,casscadeColumnName,casscadeColumnValueMap);
213 if (result.getResult() == ResultType.SUCCESS) {
214 return response.status(Status.OK)
215 .entity(new JsonResponse(result.getResult()).setMessage(result.getMessage()).toMap()).build();
218 return response.status(Status.BAD_REQUEST)
219 .entity(new JsonResponse(result.getResult()).setMessage(result.getMessage()).toMap()).build();