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