2 * ============LICENSE_START==========================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * ============LICENSE_END=============================================
20 * ====================================================================
22 package org.onap.music.conductor.conditionals;
24 import java.util.HashMap;
25 import java.util.LinkedHashMap;
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;
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 import org.onap.music.conductor.*;
55 import com.datastax.driver.core.DataType;
56 import com.datastax.driver.core.TableMetadata;
58 import io.swagger.annotations.Api;
59 import io.swagger.annotations.ApiParam;
61 @Path("/v2/conditional")
62 @Api(value = "Conditional Api", hidden = true)
63 public class RestMusicConditionalAPI {
64 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class);
65 private static final String XMINORVERSION = "X-minorVersion";
66 private static final String XPATCHVERSION = "X-patchVersion";
67 private static final String NS = "ns";
68 private static final String VERSION = "v2";
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 = "Authorization", required = true) @HeaderParam("Authorization") String authorization,
81 @ApiParam(value = "Major Version", required = true) @PathParam("keyspace") String keyspace,
82 @ApiParam(value = "Major Version", required = true) @PathParam("tablename") String tablename,
83 JsonConditional jsonObj) throws Exception {
84 ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
85 String primaryKey = jsonObj.getPrimaryKey();
86 String primaryKeyValue = jsonObj.getPrimaryKeyValue();
87 String casscadeColumnName = jsonObj.getCasscadeColumnName();
88 Map<String, Object> tableValues = jsonObj.getTableValues();
89 Map<String, Object> casscadeColumnData = jsonObj.getCasscadeColumnData();
90 Map<String, Map<String, String>> conditions = jsonObj.getConditions();
92 if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null || tableValues.isEmpty()
93 || casscadeColumnData.isEmpty() || conditions.isEmpty()) {
94 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
95 ErrorTypes.AUTHENTICATIONERROR);
96 return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE)
97 .setError(String.valueOf("One or more input values missing")).toMap()).build();
100 Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
101 String userId = userCredentials.get(MusicUtil.USERID);
102 String password = userCredentials.get(MusicUtil.PASSWORD);
104 Map<String, Object> authMap = null;
106 authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "insertIntoTable");
107 } catch (Exception e) {
108 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
109 ErrorTypes.AUTHENTICATIONERROR);
110 return response.status(Status.UNAUTHORIZED)
111 .entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
113 if (authMap.containsKey("aid"))
114 authMap.remove("aid");
115 if (!authMap.isEmpty()) {
116 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
117 ErrorTypes.AUTHENTICATIONERROR);
118 return response.status(Status.UNAUTHORIZED).entity(
119 new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap())
123 Map<String, Object> valuesMap = new LinkedHashMap<>();
124 for (Map.Entry<String, Object> entry : tableValues.entrySet()) {
125 valuesMap.put(entry.getKey(), entry.getValue());
128 Map<String, String> status = new HashMap<>();
129 status.put("exists", conditions.get("exists").get("status").toString());
130 status.put("nonexists", conditions.get("nonexists").get("status").toString());
131 ReturnType out = null;
133 out = MusicConditional.conditionalInsert(keyspace, tablename, casscadeColumnName, casscadeColumnData,
134 primaryKeyValue, valuesMap, status);
135 return response.status(Status.OK).entity(new JsonResponse(out.getResult()).setMessage(out.getMessage()).toMap())
140 @SuppressWarnings("unchecked")
142 @Path("/update/keyspaces/{keyspace}/tables/{tablename}")
143 @Consumes(MediaType.APPLICATION_JSON)
144 @Produces(MediaType.APPLICATION_JSON)
145 public Response updateConditional(
146 @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
147 @ApiParam(value = "Minor Version", required = false) @HeaderParam(XMINORVERSION) String minorVersion,
148 @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
149 @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
150 @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns,
151 @ApiParam(value = "Authorization", required = true) @HeaderParam("Authorization") String authorization,
152 @ApiParam(value = "Major Version", required = true) @PathParam("keyspace") String keyspace,
153 @ApiParam(value = "Major Version", required = true) @PathParam("tablename") String tablename,
154 JsonConditional upObj) throws Exception {
155 ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
157 String primaryKey = upObj.getPrimaryKey();
158 String primaryKeyValue = upObj.getPrimaryKeyValue();
159 String casscadeColumnName = upObj.getCasscadeColumnName();
160 Map<String, Object> casscadeColumnData = upObj.getCasscadeColumnData();
161 Map<String, Object> tableValues = upObj.getTableValues();
163 if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null
164 || casscadeColumnData.isEmpty()) {
165 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
166 ErrorTypes.AUTHENTICATIONERROR);
167 return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE)
168 .setError(String.valueOf("One or more input values missing")).toMap()).build();
171 Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
172 String userId = userCredentials.get(MusicUtil.USERID);
173 String password = userCredentials.get(MusicUtil.PASSWORD);
175 Map<String, Object> authMap = null;
177 authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "updateTable");
178 } catch (Exception e) {
179 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
180 ErrorTypes.AUTHENTICATIONERROR);
181 return response.status(Status.UNAUTHORIZED)
182 .entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
184 if (authMap.containsKey("aid"))
185 authMap.remove("aid");
186 if (!authMap.isEmpty()) {
187 logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
188 ErrorTypes.AUTHENTICATIONERROR);
189 return response.status(Status.UNAUTHORIZED).entity(
190 new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap())
194 String planId = casscadeColumnData.get("key").toString();
195 Map<String,String> casscadeColumnValueMap = (Map<String, String>) casscadeColumnData.get("value");
196 TableMetadata tableInfo = null;
197 tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename);
198 DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType();
199 String primaryId = tableInfo.getPrimaryKey().get(0).getName();
201 PreparedQueryObject select = new PreparedQueryObject();
202 select.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " where " + primaryId + " = ?");
203 select.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKeyValue));
205 PreparedQueryObject upsert = MusicConditional.extractQuery(tableValues, tableInfo, tablename, keyspace, primaryKey, primaryKeyValue, null, null);
206 Map<String,PreparedQueryObject> queryBank = new HashMap<>();
207 queryBank.put(MusicUtil.SELECT, select);
208 queryBank.put(MusicUtil.UPSERT, upsert);
209 ReturnType result = MusicConditional.update(queryBank, keyspace, tablename, primaryKey,primaryKeyValue,planId,casscadeColumnName,casscadeColumnValueMap);
210 if (result.getResult() == ResultType.SUCCESS) {
211 return response.status(Status.OK)
212 .entity(new JsonResponse(result.getResult()).setMessage(result.getMessage()).toMap()).build();
215 return response.status(Status.BAD_REQUEST)
216 .entity(new JsonResponse(result.getResult()).setMessage(result.getMessage()).toMap()).build();