Changes Listed below:
[music.git] / src / main / java / org / onap / music / conductor / conditionals / RestMusicConditionalAPI.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
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
12  * 
13  *     http://www.apache.org/licenses/LICENSE-2.0
14  * 
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.
20  * 
21  * ============LICENSE_END=============================================
22  * ====================================================================
23  */
24
25 package org.onap.music.conductor.conditionals;
26
27 import java.util.HashMap;
28 import java.util.LinkedHashMap;
29 import java.util.Map;
30
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;
42
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.MusicAAFAuthentication;
56 import org.onap.music.authentication.MusicAuthenticator;
57 import org.onap.music.authentication.MusicAuthenticator.Operation;
58 import org.onap.music.conductor.*;
59
60 import com.datastax.driver.core.DataType;
61 import com.datastax.driver.core.TableMetadata;
62
63 import io.swagger.annotations.Api;
64 import io.swagger.annotations.ApiParam;
65
66 @Path("/v2/conditional")
67 @Api(value = "Conditional Api", hidden = true)
68     public class RestMusicConditionalAPI {
69     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class);
70     private static final String XMINORVERSION = "X-minorVersion";
71     private static final String XPATCHVERSION = "X-patchVersion";
72     private static final String NS = "ns";
73     private static final String VERSION = "v2";
74
75     private MusicAuthenticator authenticator = new MusicAAFAuthentication();
76
77     @POST
78     @Path("/insert/keyspaces/{keyspace}/tables/{tablename}")
79     @Consumes(MediaType.APPLICATION_JSON)
80     @Produces(MediaType.APPLICATION_JSON)
81     public Response insertConditional(
82             @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
83             @ApiParam(value = "Minor Version", required = false) @HeaderParam(XMINORVERSION) String minorVersion,
84             @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
85             @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
86             @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns,
87             @ApiParam(value = "Authorization", required = true) @HeaderParam("Authorization") String authorization,
88             @ApiParam(value = "Keyspace Name", required = true) @PathParam("keyspace") String keyspace,
89             @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename,
90             JsonConditional jsonObj) throws Exception {
91         ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
92         
93         if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.INSERT_INTO_TABLE)) {
94             return response.status(Status.UNAUTHORIZED)
95                     .entity(new JsonResponse(ResultType.FAILURE)
96                             .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
97                             .toMap()).build();
98         }
99         
100         String primaryKey = jsonObj.getPrimaryKey();
101         String primaryKeyValue = jsonObj.getPrimaryKeyValue();
102         String casscadeColumnName = jsonObj.getCasscadeColumnName();
103         Map<String, Object> tableValues = jsonObj.getTableValues();
104         Map<String, Object> casscadeColumnData = jsonObj.getCasscadeColumnData();
105         Map<String, Map<String, String>> conditions = jsonObj.getConditions();
106
107         if (primaryKey == null || primaryKeyValue == null || casscadeColumnName == null || tableValues.isEmpty()
108                 || casscadeColumnData.isEmpty() || conditions.isEmpty()) {
109             logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
110                     ErrorTypes.AUTHENTICATIONERROR);
111             return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE)
112                     .setError(String.valueOf("One or more input values missing")).toMap()).build();
113
114         }
115
116         Map<String, Object> valuesMap = new LinkedHashMap<>();
117         for (Map.Entry<String, Object> entry : tableValues.entrySet()) {
118             valuesMap.put(entry.getKey(), entry.getValue());
119         }
120
121         Map<String, String> status = new HashMap<>();
122         status.put("exists", conditions.get("exists").get("status"));
123         status.put("nonexists", conditions.get("nonexists").get("status"));
124         ReturnType out = null;
125
126         out = MusicConditional.conditionalInsert(keyspace, tablename, casscadeColumnName, casscadeColumnData,
127                 primaryKeyValue, valuesMap, status);
128         return response.status(Status.OK).entity(new JsonResponse(out.getResult()).setMessage(out.getMessage()).toMap())
129                 .build();
130
131     }
132
133     @SuppressWarnings("unchecked")
134     @PUT
135     @Path("/update/keyspaces/{keyspace}/tables/{tablename}")
136     @Consumes(MediaType.APPLICATION_JSON)
137     @Produces(MediaType.APPLICATION_JSON)
138     public Response updateConditional(
139             @ApiParam(value = "Major Version", required = true) @PathParam("version") String version,
140             @ApiParam(value = "Minor Version", required = false) @HeaderParam(XMINORVERSION) String minorVersion,
141             @ApiParam(value = "Patch Version", required = false) @HeaderParam(XPATCHVERSION) String patchVersion,
142             @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
143             @ApiParam(value = "Application namespace", required = true) @HeaderParam(NS) String ns,
144             @ApiParam(value = "Authorization", required = true) @HeaderParam("Authorization") String authorization,
145             @ApiParam(value = "Major Version", required = true) @PathParam("keyspace") String keyspace,
146             @ApiParam(value = "Major Version", required = true) @PathParam("tablename") String tablename,
147             JsonConditional upObj) throws Exception {
148         ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
149
150         if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.INSERT_INTO_TABLE)) {
151             return response.status(Status.UNAUTHORIZED)
152                     .entity(new JsonResponse(ResultType.FAILURE)
153                             .setError("Unauthorized: Please check username, password and make sure your app is onboarded")
154                             .toMap()).build();
155         }
156         
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();
162
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();
169
170         }
171
172         String planId = casscadeColumnData.get("key").toString();
173         Map<String,String> casscadeColumnValueMap = (Map<String, String>) casscadeColumnData.get("value");
174         TableMetadata tableInfo = null;
175         tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename);
176         DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType();
177         String primaryId = tableInfo.getPrimaryKey().get(0).getName();
178         
179         PreparedQueryObject select = new PreparedQueryObject();
180         select.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + " where " + primaryId + " = ?");
181         select.addValue(MusicUtil.convertToActualDataType(primaryIdType, primaryKeyValue));
182         
183         PreparedQueryObject upsert = MusicConditional.extractQuery(tableValues, tableInfo, tablename, keyspace, primaryKey, primaryKeyValue, null, null);
184         Map<String,PreparedQueryObject> queryBank = new HashMap<>();
185         queryBank.put(MusicUtil.SELECT, select);
186         queryBank.put(MusicUtil.UPSERT, upsert);
187         ReturnType result = MusicConditional.update(queryBank, keyspace, tablename, primaryKey,primaryKeyValue,planId,casscadeColumnName,casscadeColumnValueMap);
188         if (result.getResult() == ResultType.SUCCESS) {
189             return response.status(Status.OK)
190                     .entity(new JsonResponse(result.getResult()).setMessage(result.getMessage()).toMap()).build();
191         }
192         return response.status(Status.BAD_REQUEST)
193                 .entity(new JsonResponse(result.getResult()).setMessage(result.getMessage()).toMap()).build();
194
195     }
196
197 }