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.service.impl.MusicZKCore;
56 import org.onap.music.authentication.MusicAuthentication;
57 import org.onap.music.conductor.*;
59 import com.datastax.driver.core.DataType;
60 import com.datastax.driver.core.TableMetadata;
62 import io.swagger.annotations.Api;
63 import io.swagger.annotations.ApiParam;
65 @Path("/v2/conditional")
66 @Api(value = "Conditional Api", hidden = true)
67 public class RestMusicConditionalAPI {
68 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class);
69 private static final String XMINORVERSION = "X-minorVersion";
70 private static final String XPATCHVERSION = "X-patchVersion";
71 private static final String NS = "ns";
72 private static final String VERSION = "v2";
75 @Path("/insert/keyspaces/{keyspace}/tables/{tablename}")
76 @Consumes(MediaType.APPLICATION_JSON)
77 @Produces(MediaType.APPLICATION_JSON)
78 public Response insertConditional(
79 @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
80 @ApiParam(value = "Minor Version", required = false) @HeaderParam(XMINORVERSION) String minorVersion,
81 @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
82 @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
83 @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns,
84 @ApiParam(value = "Authorization", required = true) @HeaderParam("Authorization") String authorization,
85 @ApiParam(value = "Keyspace Name", required = true) @PathParam("keyspace") String keyspace,
86 @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename,
87 JsonConditional jsonObj) throws Exception {
88 ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
89 String primaryKey = jsonObj.getPrimaryKey();
90 String primaryKeyValue = jsonObj.getPrimaryKeyValue();
91 String casscadeColumnName = jsonObj.getCasscadeColumnName();
92 Map<String, Object> tableValues = jsonObj.getTableValues();
93 Map<String, Object> casscadeColumnData = jsonObj.getCasscadeColumnData();
94 Map<String, Map<String, String>> conditions = jsonObj.getConditions();
96 if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null || tableValues.isEmpty()
97 || casscadeColumnData.isEmpty() || conditions.isEmpty()) {
98 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
99 ErrorTypes.AUTHENTICATIONERROR);
100 return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE)
101 .setError(String.valueOf("One or more input values missing")).toMap()).build();
104 Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
105 String userId = userCredentials.get(MusicUtil.USERID);
106 String password = userCredentials.get(MusicUtil.PASSWORD);
108 Map<String, Object> authMap = null;
110 authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace, aid, "insertIntoTable");
111 } catch (Exception e) {
112 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
113 ErrorTypes.AUTHENTICATIONERROR);
114 return response.status(Status.UNAUTHORIZED)
115 .entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
117 if (authMap.containsKey("aid"))
118 authMap.remove("aid");
119 if (!authMap.isEmpty()) {
120 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
121 ErrorTypes.AUTHENTICATIONERROR);
122 return response.status(Status.UNAUTHORIZED).entity(
123 new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap())
127 Map<String, Object> valuesMap = new LinkedHashMap<>();
128 for (Map.Entry<String, Object> entry : tableValues.entrySet()) {
129 valuesMap.put(entry.getKey(), entry.getValue());
132 Map<String, String> status = new HashMap<>();
133 status.put("exists", conditions.get("exists").get("status"));
134 status.put("nonexists", conditions.get("nonexists").get("status"));
135 ReturnType out = null;
137 out = MusicConditional.conditionalInsert(keyspace, tablename, casscadeColumnName, casscadeColumnData,
138 primaryKeyValue, valuesMap, status);
139 return response.status(Status.OK).entity(new JsonResponse(out.getResult()).setMessage(out.getMessage()).toMap())
144 @SuppressWarnings("unchecked")
146 @Path("/update/keyspaces/{keyspace}/tables/{tablename}")
147 @Consumes(MediaType.APPLICATION_JSON)
148 @Produces(MediaType.APPLICATION_JSON)
149 public Response updateConditional(
150 @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
151 @ApiParam(value = "Minor Version", required = false) @HeaderParam(XMINORVERSION) String minorVersion,
152 @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
153 @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
154 @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns,
155 @ApiParam(value = "Authorization", required = true) @HeaderParam("Authorization") String authorization,
156 @ApiParam(value = "Major Version", required = true) @PathParam("keyspace") String keyspace,
157 @ApiParam(value = "Major Version", required = true) @PathParam("tablename") String tablename,
158 JsonConditional upObj) throws Exception {
159 ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
161 String primaryKey = upObj.getPrimaryKey();
162 String primaryKeyValue = upObj.getPrimaryKeyValue();
163 String casscadeColumnName = upObj.getCasscadeColumnName();
164 Map<String, Object> casscadeColumnData = upObj.getCasscadeColumnData();
165 Map<String, Object> tableValues = upObj.getTableValues();
167 if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null
168 || casscadeColumnData.isEmpty()) {
169 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
170 ErrorTypes.AUTHENTICATIONERROR);
171 return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE)
172 .setError(String.valueOf("One or more input values missing")).toMap()).build();
175 Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
176 String userId = userCredentials.get(MusicUtil.USERID);
177 String password = userCredentials.get(MusicUtil.PASSWORD);
179 Map<String, Object> authMap = null;
181 authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace, aid, "updateTable");
182 } catch (Exception e) {
183 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
184 ErrorTypes.AUTHENTICATIONERROR);
185 return response.status(Status.UNAUTHORIZED)
186 .entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
188 if (authMap.containsKey("aid"))
189 authMap.remove("aid");
190 if (!authMap.isEmpty()) {
191 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
192 ErrorTypes.AUTHENTICATIONERROR);
193 return response.status(Status.UNAUTHORIZED).entity(
194 new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap())
198 String planId = casscadeColumnData.get("key").toString();
199 Map<String,String> casscadeColumnValueMap = (Map<String, String>) casscadeColumnData.get("value");
200 TableMetadata tableInfo = null;
201 tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename);
202 DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType();
203 String primaryId = tableInfo.getPrimaryKey().get(0).getName();
205 PreparedQueryObject select = new PreparedQueryObject();
206 select.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " where " + primaryId + " = ?");
207 select.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKeyValue));
209 PreparedQueryObject upsert = MusicConditional.extractQuery(tableValues, tableInfo, tablename, keyspace, primaryKey, primaryKeyValue, null, null);
210 Map<String,PreparedQueryObject> queryBank = new HashMap<>();
211 queryBank.put(MusicUtil.SELECT, select);
212 queryBank.put(MusicUtil.UPSERT, upsert);
213 ReturnType result = MusicConditional.update(queryBank, keyspace, tablename, primaryKey,primaryKeyValue,planId,casscadeColumnName,casscadeColumnValueMap);
214 if (result.getResult() == ResultType.SUCCESS) {
215 return response.status(Status.OK)
216 .entity(new JsonResponse(result.getResult()).setMessage(result.getMessage()).toMap()).build();
219 return response.status(Status.BAD_REQUEST)
220 .entity(new JsonResponse(result.getResult()).setMessage(result.getMessage()).toMap()).build();