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