03ebe5fe3885f15be006570b4aea00efc3661a4f
[lispflowmapping.git] / mappingservice / northbound / src / main / java / org / opendaylight / lispflowmapping / northbound / LispMappingNorthbound.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.lispflowmapping.northbound;
9
10 import java.util.List;
11
12 import javax.ws.rs.Consumes;
13 import javax.ws.rs.DELETE;
14 import javax.ws.rs.GET;
15 import javax.ws.rs.PUT;
16 import javax.ws.rs.Path;
17 import javax.ws.rs.PathParam;
18 import javax.ws.rs.Produces;
19 import javax.ws.rs.core.Context;
20 import javax.ws.rs.core.MediaType;
21 import javax.ws.rs.core.SecurityContext;
22 import javax.ws.rs.core.Response;
23
24 import org.codehaus.enunciate.jaxrs.ResponseCode;
25 import org.codehaus.enunciate.jaxrs.StatusCodes;
26 import org.codehaus.enunciate.jaxrs.TypeHint;
27 import org.opendaylight.controller.containermanager.IContainerManager;
28 import org.opendaylight.controller.northbound.commons.RestMessages;
29 import org.opendaylight.controller.northbound.commons.exception.BadRequestException;
30 import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
31 import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
32 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
33 import org.opendaylight.controller.northbound.commons.exception.InternalServerErrorException;
34 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
35 import org.opendaylight.controller.sal.authorization.Privilege;
36 import org.opendaylight.controller.sal.utils.ServiceHelper;
37 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMapping;
38 import org.opendaylight.lispflowmapping.type.AddressFamilyNumberEnum;
39 import org.opendaylight.lispflowmapping.type.LispCanonicalAddressFormatEnum;
40 import org.opendaylight.lispflowmapping.type.lisp.EidRecord;
41 import org.opendaylight.lispflowmapping.type.lisp.LocatorRecord;
42 import org.opendaylight.lispflowmapping.type.lisp.MapRegister;
43 import org.opendaylight.lispflowmapping.type.lisp.MapRequest;
44 import org.opendaylight.lispflowmapping.type.lisp.address.LispAddress;
45 import org.opendaylight.lispflowmapping.type.lisp.address.LispAddressGeneric;
46 import org.opendaylight.lispflowmapping.type.lisp.address.LispIpv4Address;
47 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.MapNotify;
48 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.MapReply;
49 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.eidtolocatorrecords.EidToLocatorRecord;
50 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.LispAddressContainer;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 @Path("/")
55 public class LispMappingNorthbound implements ILispmappingNorthbound {
56     protected static final Logger logger = LoggerFactory.getLogger(LispMappingNorthbound.class);
57     private IFlowMapping mappingService;
58
59     private String userName;
60
61     // Based on code from controller project
62     @Context
63     public void setSecurityContext(SecurityContext context) {
64         if (context != null && context.getUserPrincipal() != null) {
65             userName = context.getUserPrincipal().getName();
66         }
67     }
68
69     protected String getUserName() {
70         return userName;
71     }
72
73     public IFlowMapping getMappingService() {
74         return this.mappingService;
75     }
76
77     void setFlowMappingService(IFlowMapping mappingService) {
78         logger.trace("FlowMapping set in LispNorthbound");
79         this.mappingService = mappingService;
80     }
81
82     void unsetFlowMappingService(IFlowMapping mappingService) {
83         logger.trace("LispDAO was unset in LISP Northbound");
84         this.mappingService = null;
85     }
86
87     public void init() {
88         logger.trace("LISP Northbound Service is initialized!");
89     }
90
91     public void start() {
92         logger.info("LISP Northbound Service is up!");
93     }
94
95     public void stop() {
96         logger.info("LISP Northbound Service is down!");
97     }
98
99     public void destroy() {
100         logger.trace("LISP Northbound Service is destroyed!");
101         mappingService = null;
102     }
103
104     // Based on code from controller project
105     private void handleContainerDoesNotExist(String containerName) {
106         IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance(IContainerManager.class, this);
107         if (containerManager == null) {
108             throw new ServiceUnavailableException("Container " + containerName + RestMessages.NOCONTAINER.toString());
109         }
110
111         List<String> containerNames = containerManager.getContainerNames();
112         for (String cName : containerNames) {
113             if (cName.trim().equalsIgnoreCase(containerName.trim())) {
114                 return;
115             }
116         }
117
118         throw new ResourceNotFoundException("Container " + containerName + " " + RestMessages.NOCONTAINER.toString());
119     }
120
121     private void authorizationCheck(String containerName, Privilege privilege) {
122
123         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, privilege, this)) {
124             throw new UnauthorizedException("User is not authorized to perform this operation on container " + containerName);
125         }
126     }
127
128     private EidToLocatorRecord lookupEID(String containerName, int mask, LispAddress EID) {
129
130         ILispmappingNorthbound nbService = (ILispmappingNorthbound) ServiceHelper.getInstance(ILispmappingNorthbound.class, containerName, this);
131
132         MapRequest mapRequest = new MapRequest();
133         EidRecord EIDRecord = new EidRecord((byte) mask, EID);
134         mapRequest.addEidRecord(EIDRecord);
135         mapRequest.setSourceEid(new LispIpv4Address("127.0.0.1"));
136
137         org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.MapRequest mr = YangTransformerNB.transformMapRequest(mapRequest);
138         MapReply mapReply;
139         try {
140             mapReply = nbService.getMappingService().handleMapRequest(mr);
141         } catch (Exception e) {
142             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString() + " : There was an error looking up the EID");
143         }
144
145         if (mapReply == null) {
146             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString() + " : There was an error looking up the EID");
147         }
148
149         EidToLocatorRecord record = null;
150
151         record = mapReply.getEidToLocatorRecord().get(0);
152
153         return record;
154     }
155
156     private void keyCheck(IFlowMapping mappingService, MapRegisterNB mapRegisterNB) {
157
158         String usedKey = mapRegisterNB.getKey();
159
160         LispAddressGeneric lispAddressGeneric;
161         LispAddress lispAddress;
162         int mask;
163         String storedKey;
164
165         int numEidRecords = mapRegisterNB.getMapRegister().getEidToLocatorRecords().size();
166
167         for (int i = 0; i < numEidRecords; i++) {
168
169             lispAddressGeneric = mapRegisterNB.getMapRegister().getEidToLocatorRecords().get(i).getPrefixGeneric();
170
171             try {
172                 lispAddress = LispAddressConvertorNB.convertToLispAddress(lispAddressGeneric);
173             } catch (Exception e) {
174                 throw new BadRequestException(RestMessages.INVALIDDATA.toString() + " : Address is not valid");
175             }
176             mask = mapRegisterNB.getMapRegister().getEidToLocatorRecords().get(i).getMaskLength();
177             try {
178                 storedKey = mappingService.getAuthenticationKey(YangTransformerNB.transformLispAddress(lispAddress), mask);
179             } catch (Exception e) {
180                 throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString() + " : There was an error while retrieving the key");
181             }
182
183             if (!usedKey.equals(storedKey)) {
184                 throw new UnauthorizedException("The key used to register the mapping " + "does not match with the stored key for that mapping");
185             }
186         }
187     }
188
189     /**
190      * Add a mapping to the LISP mapping system
191      * 
192      * @param containerName
193      *            name of the container context in which the mapping needs to be
194      *            added
195      * @param mapRegisterNB
196      *            JSON object that contains the mapping information
197      * 
198      * @return Text plain confirming reception
199      * 
200      *         <pre>
201      * Example:
202      * 
203      * Request URL:
204      * http://localhost:8080/lispflowmapping/nb/v2/default/mapping
205      * 
206      * Request body in JSON:
207      * 
208      * { 
209      * "key" : "asdf", 
210      * "mapregister" : 
211      *   { 
212      *   "wantMapNotify" : true, 
213      *   "proxyMapReply" : false, 
214      *   "eidToLocatorRecords" : 
215      *     [ 
216      *       { 
217      *       "authoritative" : true, 
218      *       "prefixGeneric" : 
219      *         { 
220      *         "ipAddress" : "10.0.0.1", 
221      *         "afi" : 1
222      *         },
223      *       "mapVersion" : 3, 
224      *       "maskLength" : 32, 
225      *       "action" : "NoAction", 
226      *       "locators" : 
227      *         [ 
228      *           { 
229      *           "multicastPriority" : 3, 
230      *           "locatorGeneric" : 
231      *             { 
232      *             "ipAddress" : "3.3.3.3", 
233      *             "afi" : 1
234      *             }, 
235      *           "routed" : true, 
236      *           "multicastWeight" : 3, 
237      *           "rlocProbed" : false, 
238      *           "localLocator" : false, 
239      *           "priority" : 3, 
240      *           "weight" : 3 
241      *           } 
242      *         ], 
243      *       "recordTtl" : 3 
244      *       } 
245      *     ], 
246      *   "nonce" : 3, 
247      *   "keyId" : 0 
248      *   } 
249      * }
250      * </pre>
251      */
252
253     @Path("/{containerName}/mapping")
254     @PUT
255     @Consumes(MediaType.APPLICATION_JSON)
256     @StatusCodes({ @ResponseCode(code = 400, condition = "Invalid data passed"),
257             @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
258             @ResponseCode(code = 404, condition = "The containerName passed was not found"),
259             @ResponseCode(code = 500, condition = "Internal Server Error: Addition of mapping failed"),
260             @ResponseCode(code = 503, condition = "Service unavailable") })
261     public Response addMapping(@PathParam("containerName") String containerName, @TypeHint(MapRegisterNB.class) MapRegisterNB mapRegisterNB) {
262
263         handleContainerDoesNotExist(containerName);
264
265         authorizationCheck(containerName, Privilege.WRITE);
266
267         ILispmappingNorthbound nbService = (ILispmappingNorthbound) ServiceHelper.getInstance(ILispmappingNorthbound.class, containerName, this);
268
269         try {
270                 keyCheck(nbService.getMappingService(), mapRegisterNB);
271
272             LispAddressConvertorNB.convertGenericToLispAddresses(mapRegisterNB.getMapRegister());
273         } catch (Exception e) {
274             throw new BadRequestException(RestMessages.INVALIDDATA.toString() + " : Address is not valid");
275         }
276         // Always request MapNotify
277         mapRegisterNB.getMapRegister().setWantMapNotify(true);
278
279         org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.MapRegister mr = null;
280         try {
281             mr = YangTransformerNB.transformMapRegister(mapRegisterNB.getMapRegister());
282         } catch (Exception e) {
283             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString() + " : There was an error while converting the map register");
284
285         }
286         MapNotify mapNotify;
287         try {
288             mapNotify = nbService.getMappingService().handleMapRegister(mr);
289         } catch (Exception e) {
290             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString() + " : There was an error while registering the mapping");
291         }
292
293         if (mapNotify == null) {
294             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString() + " : There was an error while registering the mapping");
295         }
296         return Response.status(Response.Status.OK).build();
297     }
298
299     /**
300      * Retrieve a mapping from the LISP mapping system
301      * 
302      * @param containerName
303      *            name of the container context from which the mapping is going
304      *            to be retrieved
305      * @param iid
306      *            Instance-ID of the address (0 if none)
307      * 
308      * @param afi
309      *            Address Family of the address (IPv4, IPv6 or MAC)
310      * 
311      * @param address
312      *            Address of type defined by afi
313      * 
314      * @param mask
315      *            Network mask length
316      * 
317      * @return EidToLocatorRecord as a JSON object
318      * 
319      *         <pre>
320      * Example:
321      * 
322      * Request URL:
323      * http://localhost:8080/lispflowmapping/nb/v2/default/mapping/0/1/10.0.0.1/32
324      * 
325      * </pre>
326      */
327
328     private LispAddressGeneric parseAddressURL(int iid, int afi, String address, int mask) {
329         LispAddressGeneric eidGeneric = new LispAddressGeneric(afi, address);
330
331         if (iid != 0) {
332             eidGeneric = new LispAddressGeneric(AddressFamilyNumberEnum.LCAF.getIanaCode(), eidGeneric);
333             eidGeneric.setLcafType(LispCanonicalAddressFormatEnum.SEGMENT.getLispCode());
334             eidGeneric.setInstanceId(iid);
335         }
336
337         return eidGeneric;
338     }
339
340     private LispAddressGeneric parseSrcDstAddressURL(int iid, int afi, String srcAdd, int srcML, String dstAdd, int dstML) {
341         LispAddressGeneric srcGeneric = new LispAddressGeneric(afi, srcAdd);
342         LispAddressGeneric dstGeneric = new LispAddressGeneric(afi, dstAdd);
343
344         if (iid != 0) {
345             srcGeneric = new LispAddressGeneric(AddressFamilyNumberEnum.LCAF.getIanaCode(), srcGeneric);
346             srcGeneric.setLcafType(LispCanonicalAddressFormatEnum.SEGMENT.getLispCode());
347             srcGeneric.setInstanceId(iid);
348
349             dstGeneric = new LispAddressGeneric(AddressFamilyNumberEnum.LCAF.getIanaCode(), dstGeneric);
350             dstGeneric.setLcafType(LispCanonicalAddressFormatEnum.SEGMENT.getLispCode());
351             dstGeneric.setInstanceId(iid);
352         }
353
354         LispAddressGeneric address = new LispAddressGeneric(AddressFamilyNumberEnum.LCAF.getIanaCode());
355
356         address.setLcafType(LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode());
357         address.setSrcAddress(srcGeneric);
358         address.setSrcMaskLength((byte) srcML);
359         address.setDstAddress(dstGeneric);
360         address.setDstMaskLength((byte) dstML);
361
362         return address;
363     }
364
365     @Path("/{containerName}/mapping/{iid}/{afi}/{address}/{mask}")
366     @GET
367     @Produces(MediaType.APPLICATION_JSON)
368     @StatusCodes({ @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
369             @ResponseCode(code = 400, condition = "Invalid data passed"),
370             @ResponseCode(code = 404, condition = "The containerName passed was not found"),
371             @ResponseCode(code = 500, condition = "Internal Server Error: Get mapping failed"),
372             @ResponseCode(code = 503, condition = "Service unavailable") })
373     public org.opendaylight.lispflowmapping.type.lisp.EidToLocatorRecord getMapping(@PathParam("containerName") String containerName,
374             @PathParam("iid") int iid, @PathParam("afi") int afi, @PathParam("address") String address, @PathParam("mask") int mask) {
375
376         handleContainerDoesNotExist(containerName);
377
378         authorizationCheck(containerName, Privilege.READ);
379
380         LispAddressGeneric eidGeneric = parseAddressURL(iid, afi, address, mask);
381
382         LispAddress eid;
383         try {
384             eid = LispAddressConvertorNB.convertToLispAddress(eidGeneric);
385         } catch (Exception e) {
386             throw new BadRequestException(RestMessages.INVALIDDATA.toString() + " : Address is not valid");
387         }
388
389         EidToLocatorRecord record = lookupEID(containerName, mask, eid);
390
391         org.opendaylight.lispflowmapping.type.lisp.EidToLocatorRecord legacyRecord = YangTransformerNB.reTransformEidToLocatorRecord(record);
392         LispAddressConvertorNB.convertRecordToGenericAddress(legacyRecord);
393
394         return legacyRecord;
395     }
396
397     /**
398      * Retrieve a mapping from the LISP mapping system, using Source-Destination
399      * LCAF as EID
400      * 
401      * @param containerName
402      *            name of the container context from which the mapping is going
403      *            to be retrieved
404      * @param iid
405      *            Instance-ID of the addresses (0 if none)
406      * 
407      * @param afi
408      *            Address Family of the addresses (IPv4, IPv6 or MAC)
409      * 
410      * @param srcAdd
411      *            Source address of type defined by afi
412      * 
413      * @param srcML
414      *            Network mask length of the source address
415      * 
416      * @param dstAdd
417      *            Destination address of type defined by afi
418      * 
419      * @param dstML
420      *            Network mask length of the destination address
421      * 
422      * @return EidToLocatorRecord as a JSON object
423      * 
424      *         <pre>
425      * Example:
426      * 
427      * Request URL:
428      * 
429      *      http://localhost:8080/lispflowmapping/nb/v2/default/mapping/0/1/10.0.0.1/32/20.0.0.2/32
430      * 
431      * </pre>
432      */
433
434     @Path("/{containerName}/mapping/{iid}/{afi}/{srcAdd}/{srcML}/{dstAdd}/{dstML}")
435     @GET
436     @Produces(MediaType.APPLICATION_JSON)
437     @StatusCodes({ @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
438             @ResponseCode(code = 404, condition = "The containerName passed was not found"),
439             @ResponseCode(code = 503, condition = "Service unavailable") })
440     public org.opendaylight.lispflowmapping.type.lisp.EidToLocatorRecord getMapping(@PathParam("containerName") String containerName,
441             @PathParam("iid") int iid, @PathParam("afi") int afi, @PathParam("srcAdd") String srcAdd, @PathParam("srcML") int srcML,
442             @PathParam("dstAdd") String dstAdd, @PathParam("dstML") int dstML) {
443
444         handleContainerDoesNotExist(containerName);
445
446         authorizationCheck(containerName, Privilege.READ);
447
448         LispAddressGeneric eidGeneric = parseSrcDstAddressURL(iid, afi, srcAdd, srcML, dstAdd, dstML);
449
450         int mask = 0; // Not used here
451
452         EidToLocatorRecord record = lookupEID(containerName, mask, LispAddressConvertorNB.convertToLispAddress(eidGeneric));
453
454         org.opendaylight.lispflowmapping.type.lisp.EidToLocatorRecord legacyRecord = YangTransformerNB.reTransformEidToLocatorRecord(record);
455         LispAddressConvertorNB.convertRecordToGenericAddress(legacyRecord);
456
457         return legacyRecord;
458     }
459
460     /**
461      * Set the authentication key for an EID prefix
462      * 
463      * @param containerName
464      *            name of the container context in which the key needs to be set
465      * @param authKeyNB
466      *            JSON object that contains the key information
467      * 
468      * @return Text plain confirming reception
469      * 
470      *         <pre>
471      * Example:
472      * 
473      * Request URL:
474      * http://localhost:8080/lispflowmapping/nb/v2/default/key
475      * 
476      * Request body in JSON:
477      * 
478      * {
479      * "key" : "asdf",
480      * "maskLength" : 24,
481      * "address" :
482      * {
483      * "ipAddress" : "10.0.0.1",
484      * "afi" : 1
485      * }
486      * }
487      * 
488      * </pre>
489      */
490
491     @Path("/{containerName}/key")
492     @PUT
493     @Consumes(MediaType.APPLICATION_JSON)
494     @StatusCodes({ @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
495             @ResponseCode(code = 400, condition = "Invalid data passed"),
496             @ResponseCode(code = 404, condition = "The containerName passed was not found"),
497             @ResponseCode(code = 500, condition = "Internal Server Error: Addition of key failed"),
498             @ResponseCode(code = 503, condition = "Service unavailable") })
499     public Response addAuthKey(@PathParam("containerName") String containerName, @TypeHint(AuthKeyNB.class) AuthKeyNB authKeyNB) {
500
501         handleContainerDoesNotExist(containerName);
502
503         authorizationCheck(containerName, Privilege.WRITE);
504
505         LispAddress lispAddress;
506         try {
507             lispAddress = LispAddressConvertorNB.convertToLispAddress(authKeyNB.getAddress());
508         } catch (Exception e) {
509             throw new BadRequestException(RestMessages.INVALIDDATA.toString() + " : Address is not valid");
510         }
511         ILispmappingNorthbound nbService = (ILispmappingNorthbound) ServiceHelper.getInstance(ILispmappingNorthbound.class, containerName, this);
512
513         boolean success = false;
514
515         try {
516
517             success = nbService.getMappingService().addAuthenticationKey(YangTransformerNB.transformLispAddress(lispAddress),
518                     authKeyNB.getMaskLength(), authKeyNB.getKey());
519         } catch (Exception e) {
520             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString() + " : There was an error while adding the key");
521         }
522         if (!success) {
523             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString() + " : There was an error while adding the key");
524         }
525
526         return Response.status(Response.Status.OK).build();
527     }
528
529     /**
530      * Retrieve the key used to register an EID prefix
531      * 
532      * @param containerName
533      *            name of the container context from which the key is going to
534      *            be retrieved
535      * 
536      * @param afi
537      *            Address Family of the address (IPv4, IPv6 or MAC)
538      * 
539      * @param address
540      *            Address of type defined by afi
541      * 
542      * @param mask
543      *            Network mask length
544      * 
545      * @return AuthKeyNB as a JSON object
546      * 
547      *         <pre>
548      * Example:
549      * 
550      * Request URL:
551      * http://localhost:8080/lispflowmapping/nb/v2/default/key/0/1/10.0.0.1/32
552      * 
553      * </pre>
554      */
555
556     @Path("/{containerName}/key/{iid}/{afi}/{address}/{mask}")
557     @GET
558     @Produces(MediaType.APPLICATION_JSON)
559     @StatusCodes({ @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
560             @ResponseCode(code = 400, condition = "Invalid data passed"),
561             @ResponseCode(code = 404, condition = "The containerName passed was not found"),
562             @ResponseCode(code = 500, condition = "Internal Server Error: Get key failed"),
563             @ResponseCode(code = 503, condition = "Service unavailable") })
564     public AuthKeyNB getAuthKey(@PathParam("containerName") String containerName, @PathParam("iid") int iid, @PathParam("afi") int afi,
565             @PathParam("address") String address, @PathParam("mask") int mask) {
566
567         handleContainerDoesNotExist(containerName);
568
569         authorizationCheck(containerName, Privilege.READ);
570
571         LispAddressGeneric lispAddressGeneric = parseAddressURL(iid, afi, address, mask);
572
573         LispAddress lispAddress;
574
575         try {
576             lispAddress = LispAddressConvertorNB.convertToLispAddress(lispAddressGeneric);
577         } catch (Exception e) {
578             throw new BadRequestException(RestMessages.INVALIDDATA.toString() + " : Address is not valid");
579         }
580         ILispmappingNorthbound nbService = (ILispmappingNorthbound) ServiceHelper.getInstance(ILispmappingNorthbound.class, containerName, this);
581
582         String key;
583         try {
584             key = nbService.getMappingService().getAuthenticationKey(YangTransformerNB.transformLispAddress(lispAddress), mask);
585         } catch (Exception e) {
586             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString() + " : There was an error while retrieving the key");
587         }
588
589         if (key == null) {
590             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString() + " : There was an error while retrieving the key");
591         }
592
593         AuthKeyNB authKeyNB = new AuthKeyNB();
594
595         authKeyNB.setKey(key);
596         authKeyNB.setAddress(lispAddressGeneric);
597         authKeyNB.setMaskLength(mask);
598
599         return authKeyNB;
600     }
601
602     /**
603      * Retrieve a key used to register a Source-Destination LCAF EID prefix
604      * 
605      * @param containerName
606      *            name of the container context from which the key is going to
607      *            be retrieved
608      * 
609      * @param afi
610      *            Address Family of the addresses (IPv4, IPv6 or MAC)
611      * 
612      * @param srcAdd
613      *            Source address of type defined by afi
614      * 
615      * @param srcML
616      *            Network mask length of the source address
617      * 
618      * @param dstAdd
619      *            Destination address of type defined by afi
620      * 
621      * @param dstML
622      *            Network mask length of the destination address
623      * 
624      * @return AuthKeyNB as a JSON object
625      * 
626      *         <pre>
627      * Example:
628      * 
629      * Request URL:
630      * 
631      * http://localhost:8080/lispflowmapping/nb/v2/default/key/0/1/10.0.0.1/32/20.0.0.2/32
632      * 
633      * </pre>
634      */
635
636     @Path("/{containerName}/key/{iid}/{afi}/{srcAdd}/{srcML}/{dstAdd}/{dstML}")
637     @GET
638     @Produces(MediaType.APPLICATION_JSON)
639     @StatusCodes({ @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
640             @ResponseCode(code = 404, condition = "The containerName passed was not found"),
641             @ResponseCode(code = 503, condition = "Service unavailable") })
642     public AuthKeyNB getAuthKey(@PathParam("containerName") String containerName, @PathParam("iid") int iid, @PathParam("afi") int afi,
643             @PathParam("srcAdd") String srcAdd, @PathParam("srcML") int srcML, @PathParam("dstAdd") String dstAdd, @PathParam("dstML") int dstML) {
644
645         handleContainerDoesNotExist(containerName);
646
647         authorizationCheck(containerName, Privilege.READ);
648
649         LispAddressGeneric lispAddressGeneric = parseSrcDstAddressURL(iid, afi, srcAdd, srcML, dstAdd, dstML);
650
651         LispAddress lispAddress = LispAddressConvertorNB.convertToLispAddress(lispAddressGeneric);
652
653         ILispmappingNorthbound nbService = (ILispmappingNorthbound) ServiceHelper.getInstance(ILispmappingNorthbound.class, containerName, this);
654
655         int mask = 0; // Not used here
656
657         LispAddressContainer yangAddress = YangTransformerNB.transformLispAddress(lispAddress);
658
659         String key = nbService.getMappingService().getAuthenticationKey(yangAddress, mask);
660
661         if (key == null) {
662             return null;
663         }
664
665         AuthKeyNB authKeyNB = new AuthKeyNB();
666
667         authKeyNB.setKey(key);
668         authKeyNB.setAddress(lispAddressGeneric);
669         authKeyNB.setMaskLength(mask);
670
671         return authKeyNB;
672     }
673
674     /**
675      * Delete the key used to register an EID prefix
676      * 
677      * @param containerName
678      *            name of the container context from which the key is going to
679      *            be deleted
680      * 
681      * @param afi
682      *            Address Family of the address (IPv4, IPv6 or MAC)
683      * 
684      * @param address
685      *            Address of type defined by afi
686      * 
687      * @param mask
688      *            Network mask length
689      * 
690      * @return Text plain confirming deletion
691      * 
692      *         <pre>
693      * Example:
694      * 
695      * Request URL:
696      * http://localhost:8080/lispflowmapping/nb/v2/default/key/0/1/10.0.0.1/32
697      * 
698      * </pre>
699      */
700
701     @Path("/{containerName}/key/{iid}/{afi}/{address}/{mask}")
702     @DELETE
703     @StatusCodes({ @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
704             @ResponseCode(code = 400, condition = "Invalid data passed"),
705             @ResponseCode(code = 404, condition = "The containerName passed was not found"),
706             @ResponseCode(code = 500, condition = "Internal Server Error: Delete key failed"),
707             @ResponseCode(code = 503, condition = "Service unavailable") })
708     public Response delAuthKey(@PathParam("containerName") String containerName, @PathParam("afi") int afi, @PathParam("iid") int iid,
709             @PathParam("address") String address, @PathParam("mask") int mask) {
710
711         handleContainerDoesNotExist(containerName);
712
713         authorizationCheck(containerName, Privilege.WRITE);
714
715         LispAddressGeneric lispAddressGeneric = parseAddressURL(iid, afi, address, mask);
716
717         LispAddress lispAddress;
718         try {
719             lispAddress = LispAddressConvertorNB.convertToLispAddress(lispAddressGeneric);
720         } catch (Exception e) {
721             throw new BadRequestException(RestMessages.INVALIDDATA.toString() + " : Address is not valid");
722         }
723
724         ILispmappingNorthbound nbService = (ILispmappingNorthbound) ServiceHelper.getInstance(ILispmappingNorthbound.class, containerName, this);
725
726         boolean success = false;
727         try {
728             success = nbService.getMappingService().removeAuthenticationKey(YangTransformerNB.transformLispAddress(lispAddress), mask);
729         } catch (Exception e) {
730             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString() + " : There was an error while deleting the key");
731         }
732
733         if (!success) {
734             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString() + " : There was an error while deleting the key");
735         }
736
737         return Response.status(Response.Status.OK).build();
738     }
739
740     /**
741      * Delete the key used to register an EID prefix
742      * 
743      * @param containerName
744      *            name of the container context from which the key is going to
745      *            be retrieved
746      * 
747      * @param afi
748      *            Address Family of the addresses (IPv4, IPv6 or MAC)
749      * 
750      * @param srcAdd
751      *            Source address of type defined by afi
752      * 
753      * @param srcML
754      *            Network mask length of the source address
755      * 
756      * @param dstAdd
757      *            Destination address of type defined by afi
758      * 
759      * @param dstML
760      *            Network mask length of the destination address
761      * 
762      * @return AuthKeyNB as a JSON object
763      * 
764      *         <pre>
765      * Example:
766      * 
767      * Request URL:
768      * http://localhost:8080/lispflowmapping/nb/v2/default/key/0/1/10.0.0.1/32/20.0.0.2/32
769      * 
770      * </pre>
771      */
772
773     @Path("/{containerName}/key/{iid}/{afi}/{srcAdd}/{srcML}/{dstAdd}/{dstML}")
774     @DELETE
775     @StatusCodes({ @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
776             @ResponseCode(code = 400, condition = "Invalid data passed"),
777             @ResponseCode(code = 404, condition = "The containerName passed was not found"),
778             @ResponseCode(code = 500, condition = "Internal Server Error: Delete key failed"),
779             @ResponseCode(code = 503, condition = "Service unavailable") })
780     public Response delAuthKey(@PathParam("containerName") String containerName, @PathParam("iid") int iid, @PathParam("afi") int afi,
781             @PathParam("srcAdd") String srcAdd, @PathParam("srcML") int srcML, @PathParam("dstAdd") String dstAdd, @PathParam("dstML") int dstML) {
782
783         handleContainerDoesNotExist(containerName);
784
785         authorizationCheck(containerName, Privilege.WRITE);
786
787         LispAddressGeneric lispAddressGeneric = parseSrcDstAddressURL(iid, afi, srcAdd, srcML, dstAdd, dstML);
788
789         LispAddress lispAddress;
790         try {
791             lispAddress = LispAddressConvertorNB.convertToLispAddress(lispAddressGeneric);
792         } catch (Exception e) {
793             throw new BadRequestException(RestMessages.INVALIDDATA.toString() + " : Address is not valid");
794         }
795
796         ILispmappingNorthbound nbService = (ILispmappingNorthbound) ServiceHelper.getInstance(ILispmappingNorthbound.class, containerName, this);
797
798         int mask = 0; // Not used here
799
800         boolean success = false;
801         try {
802             success = nbService.getMappingService().removeAuthenticationKey(YangTransformerNB.transformLispAddress(lispAddress), mask);
803         } catch (Exception e) {
804             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString() + " : There was an error while deleting the key");
805         }
806
807         if (!success) {
808             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString() + " : There was an error while deleting the key");
809         }
810
811         return Response.status(Response.Status.OK).build();
812     }
813
814 }