Changes related to Authentication and Atomic
[music.git] / src / main / java / org / onap / music / rest / RestMusicLocksAPI.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
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
10  * 
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  * 
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.
18  * 
19  * ============LICENSE_END=============================================
20  * ====================================================================
21  */
22 package org.onap.music.rest;
23
24 import java.util.Map;
25
26 import javax.servlet.http.HttpServletResponse;
27 import javax.ws.rs.Consumes;
28 import javax.ws.rs.DELETE;
29 import javax.ws.rs.GET;
30 import javax.ws.rs.HeaderParam;
31 import javax.ws.rs.POST;
32 import javax.ws.rs.Path;
33 import javax.ws.rs.PathParam;
34 import javax.ws.rs.Produces;
35 import javax.ws.rs.core.Context;
36 import javax.ws.rs.core.MediaType;
37
38 import org.onap.music.datastore.jsonobjects.JsonLeasedLock;
39 import org.onap.music.eelf.logging.EELFLoggerDelegate;
40 import org.onap.music.lockingservice.MusicLockState;
41 import org.onap.music.main.MusicCore;
42 import org.onap.music.main.MusicUtil;
43 import org.onap.music.main.ResultType;
44 import org.onap.music.main.ReturnType;
45 import org.onap.music.response.jsonobjects.JsonLockResponse;
46
47 import io.swagger.annotations.Api;
48 import io.swagger.annotations.ApiOperation;
49 import io.swagger.annotations.ApiParam;
50
51
52 @Path("/v{version: [0-9]+}/locks/")
53 @Api(value="Lock Api")
54 public class RestMusicLocksAPI {
55
56         @SuppressWarnings("unused")
57     private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicLocksAPI.class);
58         private static String xLatestVersion = "X-latestVersion";
59
60         /**
61          * Puts the requesting process in the q for this lock. The corresponding
62          * node will be created in zookeeper if it did not already exist
63          * 
64          * @param lockName
65          * @return
66          * @throws Exception 
67          */
68
69         @POST
70         @Path("/create/{lockname}")
71         @ApiOperation(value = "Create Lock",
72                 notes = "Puts the requesting process in the q for this lock." +
73                 " The corresponding node will be created in zookeeper if it did not already exist." +
74                 " Lock Name is the \"key\" of the form keyspaceName.tableName.rowId",
75                 response = Map.class)
76         @Produces(MediaType.APPLICATION_JSON)   
77         public Map<String,Object> createLockReference(
78                         @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName,
79                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
80             @ApiParam(value = "Application namespace",
81                             required = true) @HeaderParam("ns") String ns,
82             @ApiParam(value = "userId",
83                             required = true) @HeaderParam("userId") String userId,
84             @ApiParam(value = "Password",
85                             required = true) @HeaderParam("password") String password,
86                         @Context HttpServletResponse response) throws Exception{
87                 response.addHeader(xLatestVersion,MusicUtil.getVersion());      
88                 Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, null, aid,
89                 "createLockReference");
90                 if (!resultMap.isEmpty()) {
91                 return resultMap;
92         }
93                 ResultType status = ResultType.SUCCESS;
94                 String lockId = MusicCore.createLockReference(lockName);
95                 if (lockId == null) { status = ResultType.FAILURE; }
96                 return new JsonLockResponse(status).setLock(lockId).toMap();
97         }
98
99         /**
100          * 
101          * Checks if the node is in the top of the queue and hence acquires the lock
102          * 
103          * @param lockId
104          * @return
105          * @throws Exception 
106          */
107         @GET
108         @Path("/acquire/{lockreference}")
109         @ApiOperation(value = "Aquire Lock", 
110                 notes = "Checks if the node is in the top of the queue and hence acquires the lock",
111                 response = Map.class)
112         @Produces(MediaType.APPLICATION_JSON)   
113         public Map<String,Object> accquireLock(
114                         @ApiParam(value="Lock Reference",required=true) @PathParam("lockreference") String lockId,
115                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
116             @ApiParam(value = "Application namespace",
117                             required = true) @HeaderParam("ns") String ns,
118             @ApiParam(value = "userId",
119                             required = true) @HeaderParam("userId") String userId,
120             @ApiParam(value = "Password",
121                             required = true) @HeaderParam("password") String password,
122                         @Context HttpServletResponse response) throws Exception{
123                 response.addHeader(xLatestVersion,MusicUtil.getVersion());
124                 Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, null, aid,
125                 "accquireLock");
126                 if (!resultMap.isEmpty()) {
127                 return resultMap;
128         }
129                 String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$'));
130                 ReturnType lockStatus = MusicCore.acquireLock(lockName,lockId);
131                 return new JsonLockResponse(lockStatus.getResult()).setLock(lockId)
132                                                                         .setMessage(lockStatus.getMessage()).toMap();
133         }
134         
135
136
137         
138         @POST
139         @Path("/acquire-with-lease/{lockreference}")
140         @ApiOperation(value = "Aquire Lock with Lease", response = Map.class)
141         @Consumes(MediaType.APPLICATION_JSON)
142         @Produces(MediaType.APPLICATION_JSON)   
143         public Map<String,Object> accquireLockWithLease(JsonLeasedLock lockObj, 
144                         @ApiParam(value="Lock Reference",required=true) @PathParam("lockreference") String lockId,
145                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
146             @ApiParam(value = "Application namespace",
147                             required = true) @HeaderParam("ns") String ns,
148             @ApiParam(value = "userId",
149                             required = true) @HeaderParam("userId") String userId,
150             @ApiParam(value = "Password",
151                             required = true) @HeaderParam("password") String password,
152                         @Context HttpServletResponse response) throws Exception{
153                 response.addHeader(xLatestVersion,MusicUtil.getVersion());
154                 Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, null, aid,
155                 "accquireLockWithLease");
156                 if (!resultMap.isEmpty()) {
157                 return resultMap;
158         }
159                 String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$'));
160                 ReturnType lockLeaseStatus = MusicCore.acquireLockWithLease(lockName, lockId, lockObj.getLeasePeriod());
161                 return new JsonLockResponse(lockLeaseStatus.getResult()).setLock(lockName)
162                                                                         .setMessage(lockLeaseStatus.getMessage())
163                                                                         .setLockLease(String.valueOf(lockObj.getLeasePeriod())).toMap();
164         } 
165         
166
167         @GET
168         @Path("/enquire/{lockname}")
169         @ApiOperation(value = "Get Lock Holder", 
170                 notes = "Gets the current Lock Holder",
171                 response = Map.class)
172         @Produces(MediaType.APPLICATION_JSON)   
173         public Map<String,Object> currentLockHolder(
174                         @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName,
175                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
176             @ApiParam(value = "Application namespace",
177                             required = true) @HeaderParam("ns") String ns,
178             @ApiParam(value = "userId",
179                             required = true) @HeaderParam("userId") String userId,
180             @ApiParam(value = "Password",
181                             required = true) @HeaderParam("password") String password,
182                         @Context HttpServletResponse response) throws Exception{
183                 response.addHeader(xLatestVersion,MusicUtil.getVersion());
184                 Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, null, aid,
185                 "currentLockHolder");
186                 if (!resultMap.isEmpty()) {
187                 return resultMap;
188         }
189                 String who = MusicCore.whoseTurnIsIt(lockName);
190                 ResultType status = ResultType.SUCCESS;
191                 String error = "";
192                 if ( who == null ) { 
193                         status = ResultType.FAILURE; 
194                         error = "There was a problem getting the lock holder";
195                 }
196                 return new JsonLockResponse(status).setError(error)
197                                                 .setLock(lockName).setLockHolder(who).toMap();
198         }
199
200         @GET
201         @Path("/{lockname}")
202         @ApiOperation(value = "Lock State",
203                 notes = "Returns current Lock State and Holder.",
204                 response = Map.class)
205         @Produces(MediaType.APPLICATION_JSON)   
206         public Map<String,Object> currentLockState(
207                         @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName,
208                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
209             @ApiParam(value = "Application namespace",
210                             required = true) @HeaderParam("ns") String ns,
211             @ApiParam(value = "userId",
212                             required = true) @HeaderParam("userId") String userId,
213             @ApiParam(value = "Password",
214                             required = true) @HeaderParam("password") String password,
215                         @Context HttpServletResponse response) throws Exception{
216                 response.addHeader(xLatestVersion,MusicUtil.getVersion());
217                 Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, null, aid,
218                 "currentLockState");
219                 if (!resultMap.isEmpty()) {
220                 return resultMap;
221         }
222                 MusicLockState mls = MusicCore.getMusicLockState(lockName);
223                 Map<String,Object> returnMap = null;
224                 JsonLockResponse jsonResponse = new JsonLockResponse(ResultType.FAILURE).setLock(lockName);
225                 if(mls == null) {
226                         jsonResponse.setError("");
227                         jsonResponse.setMessage("No lock object created yet..");
228                 } else { 
229                         jsonResponse.setStatus(ResultType.SUCCESS);
230                         jsonResponse.setLockStatus(mls.getLockStatus());
231                         jsonResponse.setLockHolder(mls.getLockHolder());
232                 } 
233                 return returnMap;
234         }
235
236         /**
237          * 
238          * deletes the process from the zk queue
239          * 
240          * @param lockId
241          * @throws Exception 
242          */
243         @DELETE
244         @Path("/release/{lockreference}")
245         @ApiOperation(value = "Release Lock",
246                 notes = "deletes the process from the zk queue",
247                 response = Map.class)
248         @Produces(MediaType.APPLICATION_JSON)   
249         public Map<String,Object> unLock(@PathParam("lockreference") String lockId,
250                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
251             @ApiParam(value = "Application namespace",
252                             required = true) @HeaderParam("ns") String ns,
253             @ApiParam(value = "userId",
254                             required = true) @HeaderParam("userId") String userId,
255             @ApiParam(value = "Password",
256                             required = true) @HeaderParam("password") String password,
257                         @Context HttpServletResponse response) throws Exception{
258                 response.addHeader(xLatestVersion,MusicUtil.getVersion());
259                 Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, null, aid,
260                 "unLock");
261                 if (!resultMap.isEmpty()) {
262                 return resultMap;
263         }
264                 boolean voluntaryRelease = true; 
265                 MusicLockState mls = MusicCore.releaseLock(lockId,voluntaryRelease);
266                 Map<String,Object> returnMap = null;
267                 if (mls.getLockStatus() == MusicLockState.LockStatus.UNLOCKED) {
268                         returnMap = new JsonLockResponse(ResultType.SUCCESS).setLock(lockId)
269                                                                 .setLockStatus(mls.getLockStatus()).toMap();
270                 }
271                 if (mls.getLockStatus() == MusicLockState.LockStatus.LOCKED) {
272                         returnMap = new JsonLockResponse(ResultType.FAILURE).setLock(lockId)
273                                                                 .setLockStatus(mls.getLockStatus()).toMap();
274                 }
275                 return returnMap;
276         }
277
278         /**
279          * 
280          * @param lockName
281          * @throws Exception 
282          */
283         @DELETE
284         @Path("/delete/{lockname}")
285         @ApiOperation(value = "Delete Lock", response = Map.class)
286         @Produces(MediaType.APPLICATION_JSON)   
287         public Map<String,Object> deleteLock(@PathParam("lockname") String lockName,
288                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
289             @ApiParam(value = "Application namespace",
290                             required = true) @HeaderParam("ns") String ns,
291             @ApiParam(value = "userId",
292                             required = true) @HeaderParam("userId") String userId,
293             @ApiParam(value = "Password",
294                             required = true) @HeaderParam("password") String password,
295                         @Context HttpServletResponse response) throws Exception{
296                 response.addHeader(xLatestVersion,MusicUtil.getVersion());
297                 Map<String, Object> resultMap = MusicCore.autheticateUser(ns, userId, password, null, aid,
298                 "deleteLock");
299                 if (!resultMap.isEmpty()) {
300                 return resultMap;
301         }
302                 MusicCore.deleteLock(lockName);
303                 return new JsonLockResponse(ResultType.SUCCESS).toMap();
304         }
305
306 }