Bug 9023: Fix merging of negative prefixes
[lispflowmapping.git] / integrationtest / src / test / java / org / opendaylight / lispflowmapping / integrationtest / MappingServiceIntegrationTest.java
1 /*
2  * Copyright (c) 2014, 2017 Contextream, 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.integrationtest;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertNull;
13 import static org.junit.Assert.assertTrue;
14 import static org.junit.Assert.fail;
15 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_A;
16 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_A_SB;
17 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_B;
18 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_B_SB;
19 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C;
20 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_RLOC_10;
21 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_SB;
22 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_WP_100_1_SB;
23 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_WP_50_2_SB;
24 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D4;
25 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D5;
26 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_DELETE_SB;
27 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_WP_100_1_SB;
28 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_WP_50_2_SB;
29 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_E_SB;
30 import static org.ops4j.pax.exam.CoreOptions.composite;
31 import static org.ops4j.pax.exam.CoreOptions.maven;
32 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
33
34 import com.google.common.collect.Lists;
35 import com.google.common.collect.Sets;
36 import java.io.IOException;
37 import java.net.DatagramPacket;
38 import java.net.DatagramSocket;
39 import java.net.InetAddress;
40 import java.net.InetSocketAddress;
41 import java.net.SocketException;
42 import java.net.SocketTimeoutException;
43 import java.net.UnknownHostException;
44 import java.nio.ByteBuffer;
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.List;
48 import java.util.Set;
49 import javax.inject.Inject;
50 import org.junit.After;
51 import org.junit.Assert;
52 import org.junit.Before;
53 import org.junit.Test;
54 import org.junit.runner.RunWith;
55 import org.opendaylight.controller.mdsal.it.base.AbstractMdsalTestBase;
56 import org.opendaylight.lispflowmapping.config.ConfigIni;
57 import org.opendaylight.lispflowmapping.implementation.LispMappingService;
58 import org.opendaylight.lispflowmapping.interfaces.dao.SubKeys;
59 import org.opendaylight.lispflowmapping.interfaces.dao.Subscriber;
60 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMapping;
61 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
62 import org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer;
63 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
64 import org.opendaylight.lispflowmapping.lisp.serializer.MapReplySerializer;
65 import org.opendaylight.lispflowmapping.lisp.serializer.MapRequestSerializer;
66 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
67 import org.opendaylight.lispflowmapping.lisp.util.ByteUtil;
68 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
69 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
70 import org.opendaylight.lispflowmapping.lisp.util.MappingRecordUtil;
71 import org.opendaylight.lispflowmapping.type.MappingData;
72 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispSouthboundPlugin;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.AfiListLcaf;
78 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.ApplicationDataLcaf;
79 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.ExplicitLocatorPathLcaf;
80 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.InstanceIdType;
81 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.Ipv4PrefixAfi;
82 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.KeyValueAddressLcaf;
83 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.MacAfi;
84 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SimpleAddress;
85 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SourceDestKeyLcaf;
86 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.Address;
87 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.AfiList;
88 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ApplicationData;
89 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ExplicitLocatorPath;
90 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4Prefix;
91 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4PrefixBuilder;
92 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.KeyValueAddress;
93 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Mac;
94 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.SourceDestKey;
95 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.afi.list.AfiListBuilder;
96 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.application.data.ApplicationDataBuilder;
97 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.ExplicitLocatorPathBuilder;
98 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.explicit.locator.path.Hop;
99 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.explicit.locator.path.Hop.LrsBits;
100 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.explicit.locator.path.HopBuilder;
101 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.source.dest.key.SourceDestKeyBuilder;
102 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.Ipv4AddressBinary;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.Ipv4PrefixBinaryAfi;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv4PrefixBinaryBuilder;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.AddMapping;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapNotify;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapReply;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapReply;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRequest;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAlive;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.OdlLispProtoListener;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.RequestMapping;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.SiteId;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrId;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrReplyMapping;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrRequestMapping;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.EidBuilder;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItem;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItemBuilder;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecord;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecordBuilder;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkey;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkeyBuilder;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord.Action;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecordBuilder;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItemBuilder;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapregisternotification.MapRegisterBuilder;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRloc;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRlocBuilder;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.SourceEidBuilder;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequestnotification.MapRequestBuilder;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.Rloc;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.RlocBuilder;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingOrigin;
142 import org.ops4j.pax.exam.Option;
143 import org.ops4j.pax.exam.junit.PaxExam;
144 import org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel;
145 import org.ops4j.pax.exam.options.MavenUrlReference;
146 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
147 import org.ops4j.pax.exam.spi.reactors.PerClass;
148 import org.ops4j.pax.exam.util.Filter;
149 import org.osgi.framework.Bundle;
150 import org.osgi.framework.BundleContext;
151 import org.osgi.framework.InvalidSyntaxException;
152 import org.slf4j.Logger;
153 import org.slf4j.LoggerFactory;
154
155 @RunWith(PaxExam.class)
156 @ExamReactorStrategy(PerClass.class)
157 public class MappingServiceIntegrationTest extends AbstractMdsalTestBase {
158     private static final Logger LOG = LoggerFactory.getLogger(MappingServiceIntegrationTest.class);
159
160     /**
161      * Defines how many attempt to create instance of DatagramSocket will be done before giving up.
162      */
163     private static final int NUM_OF_ATTEMPTS_TO_CREATE_SOCKET = 2;
164
165     private byte[] mapRequestPacket;
166     private byte[] mapRegisterPacketWithNotify;
167     private byte[] mapRegisterPacketWithoutNotify;
168     String lispBindAddress = "127.0.0.1";
169     static final String ourAddress = "127.0.0.2";
170     private Rloc locatorEid;
171     private DatagramSocket socket;
172     private byte[] mapRegisterPacketWithAuthenticationAndMapNotify;
173
174     public static final String ODL = "org.opendaylight.controller";
175     public static final String YANG = "org.opendaylight.yangtools";
176     private static final int MULTI_SITE_SLEEP_TIME = 2;
177     private static final int MAX_NOTIFICATION_RETRYS = 20;
178     private static final MappingAuthkey NULL_AUTH_KEY = new MappingAuthkeyBuilder().setKeyType(0).build();
179
180     // This is temporary, since the properties in the pom file are not picked up
181     @Override
182     public String getKarafDistro() {
183         return maven()
184                 .groupId("org.opendaylight.lispflowmapping")
185                 .artifactId("lispflowmapping-karaf")
186                 .versionAsInProject()
187                 .type("zip")
188                 .getURL();
189     }
190
191     @Override
192     public MavenUrlReference getFeatureRepo() {
193         return maven()
194                 .groupId("org.opendaylight.lispflowmapping")
195                 .artifactId("features-lispflowmapping")
196                 .classifier("features")
197                 .type("xml")
198                 .versionAsInProject();
199     }
200
201     @Override
202     public String getFeatureName() {
203         return "odl-lispflowmapping-msmr";
204     }
205
206     @Override
207     public Option getLoggingOption() {
208         Option option = editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
209                 "log4j.logger.org.opendaylight.lispflowmapping",
210                 LogLevel.TRACE.name());
211         option = composite(option, super.getLoggingOption());
212         return option;
213     }
214
215     @Test
216     public void testLispFlowMappingFeatureLoad() {
217         Assert.assertTrue(true);
218     }
219
220     @After
221     public void after() {
222         if (socket != null) {
223             socket.close();
224         }
225         // reset mapping record validity to default value
226         ConfigIni.getInstance().setRegistrationValiditySb(200000L);
227     }
228
229     @Before
230     public void before() throws Exception {
231         areWeReady();
232         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_FIRST);
233         mapService.setMappingMerge(false);
234         ConfigIni.getInstance().setSmrRetryCount(1);
235
236         locatorEid = LispAddressUtil.asIpv4Rloc("4.3.2.1");
237         socket = initSocket(socket, LispMessage.PORT_NUM);
238
239         // SRC: 127.0.0.1:58560 to 127.0.0.1:4342
240         // LISP(Type = 8 - Encapsulated)
241         // IP: 192.168.136.10 -> 153.16.254.1
242         // UDP: 56756
243         // LISP(Type = 1 Map-Request
244         // Record Count: 1
245         // ITR-RLOC count: 0
246         // Source EID AFI: 1
247         // Source EID 1.2.3.4
248         // Nonce: 0x3d8d2acd39c8d608
249         // ITR-RLOC AFI=1 Address=192.168.136.10
250         // Record 1: 153.16.254.1/32
251         mapRequestPacket = extractWSUdpByteArray(new String("0000   00 00 00 00 00 00 00 00 00 00 00 00 08 00 45 00 " //
252                 + "0010   00 58 00 00 40 00 40 11 3c 93 7f 00 00 01 7f 00 "
253                 + "0020   00 01 e4 c0 10 f6 00 44 fe 57 80 00 00 00 45 00 "
254                 + "0030   00 3c d4 31 00 00 ff 11 56 f3 7f 00 00 02 99 10 "
255                 + "0040   fe 01 dd b4 10 f6 00 28 ef 3a 10 00 00 01 3d 8d "
256                 + "0050   2a cd 39 c8 d6 08 00 01 01 02 03 04 00 01 7f 00 00 02 00 20 " //
257                 + "0060   00 01 99 10 fe 01"));
258
259         // IP: 192.168.136.10 -> 128.223.156.35
260         // UDP: 49289 -> 4342
261         // LISP(Type = 3 Map-Register, P=1, M=1
262         // Record Counter: 1
263         // Nonce: 0
264         // Key ID: 0x0001
265         // AuthDataLength: 20 Data:
266         // e8:f5:0b:c5:c5:f2:b0:21:27:a8:21:41:04:f3:46:5a:a5:68:89:ec
267         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
268         // No-Action
269         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
270         // Priority/Weight: 1/100, Multicast Priority/Weight:
271         // 255/0
272         //
273
274         mapRegisterPacketWithAuthenticationAndMapNotify = extractWSUdpByteArray(new String(
275                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
276                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
277                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
278                 + "0030   00 00 00 00 00 00 00 01 00 14 0e a4 c6 d8 a4 06 "
279                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
280                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
281                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
282
283         // IP: 192.168.136.10 -> 128.223.156.35
284         // UDP: 49289 -> 4342
285         // LISP(Type = 3 Map-Register, P=1, M=1
286         // Record Counter: 1
287         // Nonce: 7
288         // Key ID: 0x0000 NO AUTHENTICATION!!
289         // AuthDataLength: 00 Data:
290         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
291         // No-Action
292         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
293         // Priority/Weight: 1/100, Multicast Priority/Weight:
294         // 255/0
295         //
296
297         mapRegisterPacketWithNotify = extractWSUdpByteArray(new String(
298                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
299                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
300                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
301                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
302                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
303                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
304                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
305
306         // IP: 192.168.136.10 -> 128.223.156.35
307         // UDP: 49289 -> 4342
308         // LISP(Type = 3 Map-Register, P=1, M=1
309         // Record Counter: 1
310         // Nonce: 7
311         // Key ID: 0x0000 NO AUTHENTICATION!!
312         // AuthDataLength: 00 Data:
313         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
314         // No-Action
315         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
316         // Priority/Weight: 1/100, Multicast Priority/Weight:
317         // 255/0
318         //
319
320         mapRegisterPacketWithoutNotify = extractWSUdpByteArray(new String(
321                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
322                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
323                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 00 01 00 00 "
324                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
325                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
326                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
327                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
328     }
329
330     @Inject
331     private BundleContext bc;
332     //private HttpURLConnection connection;
333     protected static boolean notificationCalled;
334
335     @Inject @Filter(timeout=60000)
336     private IFlowMapping lms;
337
338     @Inject @Filter(timeout=60000)
339     private IMappingService mapService;
340
341     @Inject @Filter(timeout=10000)
342     private IConfigLispSouthboundPlugin configLispPlugin;
343
344     @Test
345     public void testSimpleUsage() throws Exception {
346         mapRequestSimple();
347         mapRegisterWithMapNotify();
348         mapRegisterWithMapNotifyAndMapRequest();
349         registerAndQuery__MAC();
350         mapRequestMapRegisterAndMapRequest();
351         mapRegisterWithAuthenticationWithoutConfiguringAKey();
352         mapRegisterWithoutMapNotify();
353     }
354
355     @Test
356     public void testLCAFs() throws Exception {
357         registerAndQuery__SrcDestLCAF();
358         registerAndQuery__SrcDestLCAFOverlap();
359         registerAndQuery__KeyValueLCAF();
360         //registerAndQuery__ListLCAF();
361         //registerAndQuery__ApplicationData();
362         //registerAndQuery__TrafficEngineering();
363         //registerAndQuery__SegmentLCAF();
364     }
365
366     @Test
367     public void testMask() throws Exception {
368         //testPasswordExactMatch();                     TODO commented because it needs NB
369         //testPasswordMaskMatch();                      TODO commented because it needs NB
370         eidPrefixLookupIPv4();
371         eidPrefixLookupIPv6();
372     }
373 /*
374     @Test
375     public void testNorthbound() throws Exception {
376         northboundAddKey();
377         northboundAddMapping();
378         northboundDeleteMapping();
379         northboundRetrieveKey();
380         northboundRetrieveMapping();
381         northboundRetrieveSourceDestKey();
382         northboundRetrieveSourceDestMapping();
383     }
384 */
385     @Test
386     public void testOverWriting() throws Exception {
387         //testMapRegisterDosntOverwritesOtherSubKeys(); TODO weird failure, needs debug
388
389         // TODO: remove, we don't support overwrite flag any longer and RLOCs are not saved as independent RLOC groups
390         // testMapRegisterOverwritesSameSubkey();
391         // testMapRegisterOverwritesNoSubkey();
392         // testMapRegisterDoesntOverwritesNoSubkey();
393     }
394
395     @Test
396     public void testTimeOuts() throws Exception {
397         timedOutMappingRecord();
398         mapRequestMapRegisterAndMapRequestTestTimeout();
399         //mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse();   TODO commented because it needs NB
400     }
401
402 //    @Test
403 //    public void testNonProxy() throws Throwable {
404 //        testSimpleNonProxy();
405 //        testNonProxyOtherPort();
406 //        testRecievingNonProxyOnXtrPort();
407 //    }
408
409     @Test
410     public void testSmr() throws Exception {
411         registerQueryRegisterWithSmr();
412         testRepeatedSmr();
413     }
414
415     @Test
416     public void testMultiSite() throws Exception {
417         testMultiSiteScenarioA();
418         testMultiSiteScenarioB();
419     }
420
421     @Test
422     public void testNbAndSbNegativePrefix() throws UnknownHostException {
423         insertMappings();
424         testGapIntersection();
425
426         insertMappings();
427         testMultipleMappings();
428     }
429
430     @Test
431     public void testExplicitSbNegativePrefixes() {
432         // https://bugs.opendaylight.org/show_bug.cgi?id=8679
433         testNegativePrefix();
434
435         // https://bugs.opendaylight.org/show_bug.cgi?id=9023
436         testPositiveMappingRemoval();
437     }
438
439     private void testRepeatedSmr() throws SocketTimeoutException, UnknownHostException {
440         cleanUP();
441         long timeout = ConfigIni.getInstance().getSmrTimeout();
442         ConfigIni.getInstance().setSmrRetryCount(5);
443
444         final InstanceIdType iid = new InstanceIdType(1L);
445         final Eid eid1 = LispAddressUtil.asIpv4Eid("1.1.1.1", 1L);
446         final Eid subscriberEid = LispAddressUtil.asIpv4Eid("2.2.2.2", 1L);
447         final int expectedSmrs1 = 2;
448         final int expectedSmrs2 = 3;
449
450         /* set auth */
451         final Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("0.0.0.0/0", iid);
452         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
453
454         /* add subscribers */
455         final String subscriberSrcRloc1 = "127.0.0.3";
456         final String subscriberSrcRloc2 = "127.0.0.4";
457         final Set<Subscriber> subscriberSet1 = Sets.newHashSet(newSubscriber(subscriberEid, subscriberSrcRloc1),
458                 newSubscriber(subscriberEid, subscriberSrcRloc2));
459         mapService.addData(MappingOrigin.Southbound, eid1, SubKeys.SUBSCRIBERS, subscriberSet1);
460
461         final SocketReader reader1 = startSocketReader(subscriberSrcRloc1, 15000);
462         final SocketReader reader2 = startSocketReader(subscriberSrcRloc2, 15000);
463         sleepForSeconds(1);
464
465         /* add mapping */
466         final MappingRecord mapping1 = new MappingRecordBuilder()
467                 .setEid(eid1).setTimestamp(System.currentTimeMillis()).setRecordTtl(1440).build();
468         mapService.addMapping(MappingOrigin.Northbound, eid1, null,
469                 new MappingData(MappingOrigin.Northbound, mapping1));
470
471         sleepForMilliseconds((timeout * expectedSmrs1) - (timeout / 2));
472         final List<MapRequest> requests1 = processSmrPackets(reader1, subscriberSrcRloc1, expectedSmrs1);
473         final MapReply mapReply1 = lms.handleMapRequest(
474                 new MapRequestBuilder(requests1.get(0))
475                         .setSourceEid(new SourceEidBuilder().setEid(subscriberEid).build())
476                         .setItrRloc(Lists.newArrayList(new ItrRlocBuilder()
477                                 .setRloc(LispAddressUtil.asIpv4Rloc(subscriberSrcRloc1)).build()))
478                         .setEidItem(Lists.newArrayList(new EidItemBuilder().setEid(eid1).build()))
479                         .setSmrInvoked(true)
480                         .setSmr(false).build());
481
482         // sleep to get 1 extra smr request
483         sleepForMilliseconds(timeout * 1);
484         final List<MapRequest> requests2 = processSmrPackets(reader2, subscriberSrcRloc2, expectedSmrs2);
485         final MapReply mapReply2 = lms.handleMapRequest(
486                 new MapRequestBuilder(requests2.get(0))
487                         .setSourceEid(new SourceEidBuilder().setEid(subscriberEid).build())
488                         .setItrRloc(Lists.newArrayList(new ItrRlocBuilder()
489                                 .setRloc(LispAddressUtil.asIpv4Rloc(subscriberSrcRloc2)).build()))
490                         .setEidItem(Lists.newArrayList(new EidItemBuilder().setEid(eid1).build()))
491                         .setSmrInvoked(true)
492                         .setSmr(false).build());
493
494         sleepForSeconds(3);
495         assertEquals(expectedSmrs1, requests1.size());
496         assertEquals(expectedSmrs2, requests2.size());
497         assertEquals((long) mapReply1.getNonce(), (long) requests1.get(0).getNonce());
498         assertEquals((long) mapReply2.getNonce(), (long) requests2.get(0).getNonce());
499         assertNextBufferEmpty(reader1);
500         assertNextBufferEmpty(reader2);
501
502         reader1.stopReading();
503         reader2.stopReading();
504     }
505
506     private SocketReader startSocketReader(String address, int timeout) {
507         DatagramSocket receivingSocket = null;
508
509         try {
510             receivingSocket = new DatagramSocket(new InetSocketAddress(address, LispMessage.PORT_NUM));
511         } catch (SocketException e) {
512             LOG.error("Can't initialize socket for {}", address, e);
513         }
514         return SocketReader.startReadingInStandaloneThread(receivingSocket, timeout);
515     }
516
517     private List<MapRequest> processSmrPackets(SocketReader reader, String address, int expectedSmrs) {
518         InetAddress inetAddress = null;
519         try {
520             inetAddress = InetAddress.getByName(address);
521         } catch (UnknownHostException e) {
522             LOG.error("Unknown address {}.", address, e);
523         }
524
525         final List<MapRequest> requests = Lists.newArrayList();
526         byte[][] buffers = reader.getBuffers(expectedSmrs);
527         for (byte[] buf : buffers) {
528             MapRequest request = MapRequestSerializer.getInstance().deserialize(ByteBuffer.wrap(buf), inetAddress);
529             requests.add(request);
530         }
531         return requests;
532     }
533
534     private void assertNextBufferEmpty(SocketReader socketReader) {
535         assertTrue(MultiSiteScenario.areBuffersEmpty(socketReader.getBuffers(1)));
536     }
537
538     private static Subscriber newSubscriber(Eid srcEid, String srcRlocIp) {
539         final int timeout = 5;
540         final Rloc srcRloc = LispAddressUtil.asIpv4Rloc(srcRlocIp);
541         return new Subscriber(srcRloc, srcEid, timeout);
542     }
543
544     private void testMultipleMappings() throws UnknownHostException {
545         final InstanceIdType iid = new InstanceIdType(1L);
546         final String prefix1 = "1.1.127.10/32"; // prefix from the intersection of NB and SB gaps
547         final String prefix2 = "1.1.200.255/32"; // prefix with existing mapping in NB
548         final String prefix3 = "1.3.255.255/32";
549
550         final MapRequest mapRequest = new MapRequestBuilder().setSmrInvoked(false).setEidItem(Lists.newArrayList(
551                 new EidItemBuilder().setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix1, iid))
552                         .build(),
553                 new EidItemBuilder().setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix2, iid))
554                         .build(),
555                 new EidItemBuilder().setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix3, iid))
556                         .build()))
557                 .build();
558         final MapReply mapReply = lms.handleMapRequest(mapRequest);
559
560         // expected result
561         final String resultPrefix1 = "1.1.64.0";
562         final Address resultNegMapping1 = new Ipv4PrefixBinaryBuilder()
563                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix1).getAddress()))
564                 .setIpv4MaskLength((short) 18).build();
565
566         final String resultPrefix2 = "1.1.128.0";
567         final Address resultMapping2 = new Ipv4PrefixBinaryBuilder()
568                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix2).getAddress()))
569                 .setIpv4MaskLength((short) 17).build();
570
571         final String resultPrefix3 = "1.3.0.0";
572         final Address resultNegMapping3 = new Ipv4PrefixBinaryBuilder()
573                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix3).getAddress()))
574                 .setIpv4MaskLength((short) 16).build();
575
576         assertEquals(resultNegMapping1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getEid()
577                 .getAddress());
578         assertEquals(resultMapping2, mapReply.getMappingRecordItem().get(1).getMappingRecord().getEid()
579                 .getAddress());
580         assertEquals(resultNegMapping3, mapReply.getMappingRecordItem().get(2).getMappingRecord().getEid()
581                 .getAddress());
582     }
583
584     /**
585      * Tests a negative mapping from an intersection of gaps in northbound and southbound.
586      */
587     private void testGapIntersection() throws UnknownHostException {
588         // request an Eid from a gap between mappings
589         final MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "1.1.127.10/32"));
590
591         // expected negative mapping
592         final Address resultNegMapping = new Ipv4PrefixBinaryBuilder()
593                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName("1.1.64.0").getAddress()))
594                 .setIpv4MaskLength((short) 18).build();
595         assertEquals(resultNegMapping, mapReply.getMappingRecordItem().get(0).getMappingRecord().getEid()
596                 .getAddress());
597     }
598
599     private void testNegativePrefix() {
600         // First, we test with one mapping in NB and one mapping in SB
601         cleanUP();
602
603         insertNBMappings(1L, "192.0.2.0/24");
604         insertSBMappings(1L, "10.0.0.0/32");
605
606         restartSocket();
607         sleepForSeconds(2);
608
609         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "11.1.1.1/32"));
610         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "11.0.0.0/8");
611         assertEquals(expectedNegativePrefix, mapReply.getMappingRecordItem().get(0).getMappingRecord().getEid());
612         assertTrue(MappingRecordUtil.isNegativeMapping(mapReply.getMappingRecordItem().get(0).getMappingRecord()));
613
614         // Second, we test with two mappings in NB only
615         cleanUP();
616
617         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
618
619         restartSocket();
620         sleepForSeconds(2);
621
622         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
623         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
624         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
625         assertEquals(expectedNegativePrefix, mr.getEid());
626         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
627     }
628
629     private void testPositiveMappingRemoval() {
630         cleanUP();
631
632         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
633         insertSBMappings(1L, "192.168.32.0/19");
634
635         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
636         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/19");
637         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
638         assertEquals(expectedNegativePrefix, mr.getEid());
639         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
640
641         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.64.1/32"));
642         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.64.0/18");
643         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
644         assertEquals(expectedNegativePrefix, mr.getEid());
645         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
646
647         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.128.1/32"));
648         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.128.0/17");
649         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
650         assertEquals(expectedNegativePrefix, mr.getEid());
651         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
652
653         printMapCacheState();
654
655         mapService.removeMapping(MappingOrigin.Southbound, LispAddressUtil.asIpv4PrefixBinaryEid(
656                 1L, "192.168.32.0/19"));
657
658         printMapCacheState();
659
660         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.32.1/32"));
661         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
662         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
663         assertEquals(expectedNegativePrefix, mr.getEid());
664         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
665
666         printMapCacheState();
667     }
668
669     private void insertMappings() {
670         cleanUP();
671         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_AND_SB);
672
673         insertNBMappings(1L, "1.2.0.0/16", "1.1.128.0/17");
674         insertSBMappings(1L, "1.1.32.0/19", "1.0.0.0/8");
675
676         restartSocket();
677         sleepForSeconds(2);
678     }
679
680     private void insertNBMappings(long iid, String ... prefixes) {
681         LOG.debug("Adding Northbound mappings for prefixes: {}", prefixes);
682         final InstanceIdType iiType = new InstanceIdType(iid);
683         for (String prefix : prefixes) {
684             MappingRecord record = newMappingRecord(prefix, iiType);
685             mapService.addMapping(MappingOrigin.Northbound, record.getEid(), null,
686                     new MappingData(MappingOrigin.Northbound, record));
687         }
688         sleepForMilliseconds(25);
689         printMapCacheState();
690     }
691
692     private void insertSBMappings(long iid, String ... prefixes) {
693         LOG.debug("Adding Southbound mappings for prefixes: {}", prefixes);
694         final InstanceIdType iiType = new InstanceIdType(iid);
695         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("0.0.0.0/0", iiType);
696         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
697
698         for (String prefix : prefixes) {
699             MappingRecord record = newMappingRecord(prefix, iiType);
700             mapService.addMapping(MappingOrigin.Southbound, record.getEid(), null,
701                     new MappingData(MappingOrigin.Southbound, record, System.currentTimeMillis()));
702         }
703         printMapCacheState();
704     }
705
706     private void printMapCacheState() {
707         LOG.debug("Map-cache state:\n{}", mapService.prettyPrintMappings());
708     }
709
710     /**
711      * Creates a new MappingRecord object.
712      *
713      * @param prefix The Eid prefix
714      * @param iid VNI
715      * @return new MappingRecord object
716      */
717     private MappingRecord newMappingRecord(String prefix, InstanceIdType iid) {
718         final Eid prefixBinary = LispAddressUtil.asIpv4PrefixBinaryEid(prefix, iid);
719         return new MappingRecordBuilder()
720                 .setEid(prefixBinary)
721                 .setLocatorRecord(Lists.newArrayList(new LocatorRecordBuilder()
722                         .setRloc(LispAddressUtil.asIpv4Rloc("2.2.2.2"))
723                         .setLocatorId("loc_id")
724                         .setRouted(true)
725                         .setPriority((short) 1)
726                         .setWeight((short) 1).build()))
727                 .setTimestamp(System.currentTimeMillis())
728                 .setRecordTtl(1440).build();
729     }
730
731     private MapRequest newMapRequest(long iid, String prefix) {
732         final InstanceIdType iidt = new InstanceIdType(iid);
733         return new MapRequestBuilder()
734                 .setSmrInvoked(false)
735                 .setEidItem(Lists.newArrayList(
736                         new EidItemBuilder().setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix, iidt)).build()))
737                 .build();
738     }
739
740     /**
741      * TEST SCENARIO A
742      */
743     public void testMultiSiteScenarioA() throws IOException {
744         cleanUP();
745         ConfigIni.getInstance().setSmrRetryCount(1);
746         ConfigIni.getInstance().setSmrTimeout(30000L);
747
748         final MultiSiteScenario multiSiteScenario = new MultiSiteScenario(mapService, lms);
749         multiSiteScenario.setCommonAuthentication();
750
751         restartSocket();
752         final SocketReader socketReader = SocketReader.startReadingInStandaloneThread(socket);
753
754         //TEST CASE 1
755         multiSiteScenario.storeSouthboundMappings(false, SITE_A, SITE_B, SITE_C, SITE_D4, SITE_D5);
756         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C);
757         multiSiteScenario.storeNorthMappingNegative(SITE_C, Action.Drop);
758         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
759         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
760         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
761         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
762
763         //TEST CASE 2
764         //following action should trigger generating of SMR messages:
765         // 1) 192.0.2.5/32
766         // 2) 192.0.1.1/32
767         multiSiteScenario.storeNorthMappingSrcDst(SITE_A, SITE_C);
768         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
769         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1));
770         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_C, 4);
771         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
772         multiSiteScenario.assertPingFails(SITE_D4, 5, SITE_C, 4);
773
774         //TEST CASE 3
775         // following action should trigger generating of SMR messages:
776         // 1) 192.0.2.5/32
777         // 2) 192.0.1.1/32
778         // 3) 192.0.1.5/32
779         // 4) 192.0.4.5/32
780         multiSiteScenario.deleteNorthMappingNegative(SITE_C);
781         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
782         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1), SITE_A
783                         .getHost(5),
784                 SITE_D4.getHost(5));
785         multiSiteScenario.assertPingWorks(SITE_D4, 5, SITE_C, 4);
786
787         //TEST CASE 4
788         // following action should trigger generating of SMR messages:
789         // 1) 192.0.2.5/32
790         // 2) 192.0.1.1/32
791         // 3) 192.0.1.5/32
792         // 4) 192.0.4.5/32
793         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C_RLOC_10);
794         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
795         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1),
796                 SITE_A.getHost(5), SITE_D4.getHost(5));
797         //way of testing ping - get RLOC for mapping src-dst and compare it with awaited value doesn't test
798         //that ping won't be successfull
799         multiSiteScenario.assertPingFails(SITE_B, 5, SITE_C, 4);
800
801         //TEST CASE 5
802         // following action should trigger generating of SMR messages:
803         // 1) 192.0.2.5/32
804         // 2) 192.0.1.1/32
805         // 3) 192.0.1.5/32
806         // 4) 192.0.4.5/32
807         multiSiteScenario.storeNorthMappingNegative(SITE_C, Action.Drop);
808         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
809         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1),
810                 SITE_A.getHost(5), SITE_D4.getHost(5));
811         multiSiteScenario.assertPingFails(SITE_D4, 5, SITE_C, 4);
812
813         //TEST CASE 6
814         multiSiteScenario.assertPingFails(SITE_D5, 5, SITE_C, 3);
815
816         //TEST CASE 7
817         // following action should trigger generating of SMR messages:
818         // 1) 192.0.4.5/32
819         // 2) 192.0.2.5/32
820         // 3) 192.0.5.5/32
821         // 4) 192.0.1.5/32
822         // 5) 192.0.1.1/32
823         multiSiteScenario.deleteNorthMapingSrcDst(SITE_A, SITE_C);
824         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
825         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
826                 SITE_B.getHost(5), SITE_A.getHost(1), SITE_A.getHost(5));
827
828         // following action should trigger generating of SMR messages:
829         // 1) 192.0.4.5/32
830         // 2) 192.0.2.5/32
831         // 3) 192.0.5.5/32
832         // 4) 192.0.1.5/32
833         // 5) 192.0.1.1/32
834         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C);
835         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
836         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
837                 SITE_B.getHost(5), SITE_A.getHost(1), SITE_A.getHost(5));
838
839         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
840         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
841         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
842
843         //TEST CASE 8
844         // following action should trigger generating of SMR messages:
845         // 1) 192.0.4.5/32
846         // 2) 192.0.2.5/32
847         // 3) 192.0.5.5/32
848         // 4) 192.0.1.5/32
849         // 5) 192.0.1.1/32
850         multiSiteScenario.deleteNorthMapingSrcDst(SITE_B, SITE_C);
851         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
852         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
853                 SITE_B.getHost(5), SITE_A.getHost(1), SITE_A.getHost(5));
854         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
855         multiSiteScenario.assertPingFails(SITE_B, 5, SITE_C, 4);
856         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
857
858         //TEST CASE 9
859         // following action should trigger generating of SMR messages:
860         // 1) 192.0.4.5/32
861         // 2) 192.0.2.5/32
862         // 3) 192.0.5.5/32
863         // 4) 192.0.1.5/32
864         // 5) 192.0.1.1/32
865         multiSiteScenario.deleteNorthMappingNegative(SITE_C);
866         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
867         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
868                 SITE_B.getHost(5), SITE_A.getHost(1), SITE_A.getHost(5));
869         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
870         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
871         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_C, 4);
872
873         socketReader.stopReading();
874
875     }
876
877     /**
878      * TEST SCENARIO B
879      */
880     public void testMultiSiteScenarioB() throws IOException {
881         cleanUP();
882
883         final MultiSiteScenario multiSiteScenario = new MultiSiteScenario(mapService, lms);
884         multiSiteScenario.setCommonAuthentication();
885
886         restartSocket();
887         final SocketReader socketReader = SocketReader.startReadingInStandaloneThread(socket);
888
889         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_AND_SB);
890         mapService.setMappingMerge(true);
891
892         //TEST CASE 1
893         multiSiteScenario.storeSouthboundMappings(true, SITE_A_SB, SITE_B_SB, SITE_C_WP_100_1_SB, SITE_D_WP_100_1_SB,
894                 SITE_E_SB);
895         multiSiteScenario.storeNorthMappingIpPrefix(SITE_A_SB);
896         multiSiteScenario.storeNorthMappingIpPrefix(SITE_B_SB);
897         multiSiteScenario.storeNorthMappingIpPrefix(SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
898         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
899         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
900         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
901
902         //TEST CASE 2
903         // following action should trigger generating of SMR messages:
904         // 1) 192.0.2.5/32
905         // 2) 192.0.1.5/32
906         multiSiteScenario.storeNorthMappingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
907         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
908         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
909
910         // following action should trigger generating of SMR messages:
911         // 1) 192.0.2.5/32
912         // 2) 192.0.1.5/32
913         multiSiteScenario.storeNorthMappingNegative(SITE_C_SB, Action.Drop);
914         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
915         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
916
917         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
918         multiSiteScenario.assertPingFails(SITE_B_SB, 5, SITE_C_SB, 4);
919
920
921         //TEST CASE 3
922         // following action should trigger generating of SMR messages:
923         // 1) 192.0.2.5/32
924         // 2) 192.0.1.5/32
925         multiSiteScenario.storeNorthMappingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB);
926         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
927         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
928         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4);
929
930         //TEST CASE 4
931         multiSiteScenario.storeNorthMappingSrcDst(SITE_B_SB, SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
932         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
933         // following action should trigger generating of SMR messages:
934         // 1) 192.0.2.5/32
935         // 2) 192.0.1.5/32
936         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
937         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
938
939         //TEST CASE 5
940         multiSiteScenario.deleteSouthboundMappings(SITE_D_DELETE_SB);
941         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
942         // following action should trigger generating of SMR messages:
943         // 1) 192.0.2.5/32
944         // 2) 192.0.1.5/32
945         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
946
947         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4);
948
949         //TEST CASE 6
950         multiSiteScenario.deleteNorthMapingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB);
951         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
952         // following action should trigger generating of SMR messages:
953         // 1) 192.0.2.5/32
954         // 2) 192.0.1.5/32
955         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
956
957         multiSiteScenario.deleteNorthMapingSrcDst(SITE_B_SB, SITE_C_WP_50_2_SB);
958         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
959         multiSiteScenario.assertPingFails(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4);
960
961         socketReader.stopReading();
962
963     }
964
965     // ------------------------------- Simple Tests ---------------------------
966
967     public void mapRequestSimple() throws SocketTimeoutException {
968         cleanUP();
969
970         // This Map-Request is sent from a source port different from 4342
971         // We close and bind the socket on the correct port
972         if (socket != null) {
973             socket.close();
974         }
975         socket = initSocket(socket, 56756);
976
977         sendPacket(mapRequestPacket);
978         ByteBuffer readBuf = ByteBuffer.wrap(receivePacket().getData());
979         MapReply reply = MapReplySerializer.getInstance().deserialize(readBuf);
980         assertEquals(4435248268955932168L, reply.getNonce().longValue());
981
982     }
983
984     public void mapRegisterWithMapNotify() throws SocketTimeoutException {
985         cleanUP();
986         mapService.addAuthenticationKey(LispAddressUtil.asIpv4PrefixBinaryEid("153.16.254.1/32"), NULL_AUTH_KEY);
987
988         sleepForSeconds(2);
989         sendPacket(mapRegisterPacketWithNotify);
990         MapNotify reply = receiveMapNotify();
991         assertEquals(7, reply.getNonce().longValue());
992     }
993
994     public void mapRegisterWithMapNotifyAndMapRequest() throws SocketTimeoutException {
995         cleanUP();
996         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
997
998         MapReply mapReply = registerAddressAndQuery(eid);
999
1000         assertEquals(4, mapReply.getNonce().longValue());
1001         assertEquals(locatorEid, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1002                 .getRloc());
1003
1004     }
1005
1006     public void registerAndQuery__MAC() throws SocketTimeoutException {
1007         cleanUP();
1008         String macAddress = "01:02:03:04:05:06";
1009
1010         MapReply reply = registerAddressAndQuery(LispAddressUtil.asMacEid(macAddress));
1011
1012         assertTrue(true);
1013         Eid addressFromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1014         assertEquals(MacAfi.class, addressFromNetwork.getAddressType());
1015         String macAddressFromReply = ((Mac) addressFromNetwork.getAddress()).getMac().getValue();
1016
1017         assertEquals(macAddress, macAddressFromReply);
1018     }
1019
1020     public void mapRequestMapRegisterAndMapRequest() throws SocketTimeoutException {
1021         cleanUP();
1022         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1023         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1024         sleepForSeconds(1);
1025
1026         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1027         mapRequestBuilder.setNonce((long) 4);
1028         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
1029         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1030         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1031         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1032         mapRequestBuilder.getItrRloc().add(
1033                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1034         sendMapRequest(mapRequestBuilder.build());
1035         MapReply mapReply = receiveMapReply();
1036         assertEquals(4, mapReply.getNonce().longValue());
1037         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1038         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
1039         mapRegisterbuilder.setWantMapNotify(true);
1040         mapRegisterbuilder.setNonce((long) 8);
1041         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1042         etlrBuilder.setEid(eid);
1043         etlrBuilder.setRecordTtl(254);
1044         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1045         recordBuilder.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
1046         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1047         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1048         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1049         mapRegisterbuilder.getMappingRecordItem().add(
1050                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
1051         sendMapRegister(mapRegisterbuilder.build());
1052         MapNotify mapNotify = receiveMapNotify();
1053         assertEquals(8, mapNotify.getNonce().longValue());
1054         sleepForSeconds(1);
1055         sendMapRequest(mapRequestBuilder.build());
1056         mapReply = receiveMapReply();
1057         assertEquals(4, mapReply.getNonce().longValue());
1058         assertEquals(recordBuilder.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord()
1059                 .getLocatorRecord().get(0).getRloc());
1060
1061     }
1062
1063     public void testMapRegisterDosntOverwritesOtherSubKeys() throws SocketTimeoutException {
1064         cleanUP();
1065         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1066         SimpleAddress rloc1Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.1")));
1067         Rloc rloc1 = LispAddressUtil.asKeyValueAddress("subkey1", rloc1Value);
1068         SimpleAddress rloc2Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.2")));
1069         Rloc rloc2 = LispAddressUtil.asKeyValueAddress("subkey2", rloc2Value);
1070         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
1071         assertEquals(2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1072         assertEquals(rloc2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1073                 .getRloc());
1074         assertEquals(rloc1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(1)
1075                 .getRloc());
1076     }
1077
1078     public void testMapRegisterOverwritesSameSubkey() throws SocketTimeoutException {
1079         cleanUP();
1080         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1081         SimpleAddress rloc1Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.1")));
1082         Rloc rloc1 = LispAddressUtil.asKeyValueAddress("subkey1", rloc1Value);
1083         SimpleAddress rloc2Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.2")));
1084         Rloc rloc2 = LispAddressUtil.asKeyValueAddress("subkey2", rloc2Value);
1085         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
1086         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1087         assertEquals(rloc2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1088                 .getRloc());
1089     }
1090
1091     public void testMapRegisterOverwritesNoSubkey() throws SocketTimeoutException {
1092         cleanUP();
1093         mapService.setMappingMerge(false);
1094         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1095         Rloc rloc1Value = LispAddressUtil.asIpv4Rloc("4.3.2.1");
1096         Rloc rloc2Value = LispAddressUtil.asIpv4Rloc("4.3.2.2");
1097         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
1098         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1099         assertEquals(rloc2Value, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1100                 .getRloc());
1101     }
1102
1103     public void testMapRegisterDoesntOverwritesNoSubkey() throws SocketTimeoutException {
1104         cleanUP();
1105         mapService.setMappingMerge(true);
1106         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1107         Rloc rloc1Value = LispAddressUtil.asIpv4Rloc("4.3.2.1");
1108         Rloc rloc2Value = LispAddressUtil.asIpv4Rloc("4.3.2.2");
1109         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
1110         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1111         Rloc rloc1ReturnValueContainer = mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
1112                 .get(0).getRloc();
1113         Rloc rloc2ReturnValueContainer = mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
1114                 .get(1).getRloc();
1115         assertTrue((rloc1Value.equals(rloc1ReturnValueContainer) && rloc2Value.equals(rloc2ReturnValueContainer))
1116                 || (rloc1Value.equals(rloc2ReturnValueContainer) && rloc2Value.equals(rloc1ReturnValueContainer)));
1117     }
1118
1119     private MapReply sendMapRegisterTwiceWithDiffrentValues(Eid eid, Rloc rloc1, Rloc rloc2)
1120             throws SocketTimeoutException {
1121         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1122         sleepForSeconds(1);
1123         MapRegister mb = createMapRegister(eid, rloc1);
1124         MapNotify mapNotify = lms.handleMapRegister(mb).getLeft();
1125         MapRequest mr = createMapRequest(eid);
1126         MapReply mapReply = lms.handleMapRequest(mr);
1127         assertEquals(mb.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc(),
1128                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc());
1129         mb = createMapRegister(eid, rloc2);
1130         mapNotify = lms.handleMapRegister(mb).getLeft();
1131         assertEquals(8, mapNotify.getNonce().longValue());
1132         mr = createMapRequest(eid);
1133         sendMapRequest(mr);
1134         mapReply = lms.handleMapRequest(mr);
1135         return mapReply;
1136     }
1137
1138     public void mapRegisterWithAuthenticationWithoutConfiguringAKey() throws SocketTimeoutException {
1139         cleanUP();
1140         sendPacket(mapRegisterPacketWithAuthenticationAndMapNotify);
1141         try {
1142             receivePacket(3000);
1143             // If didn't timeout then fail:
1144             fail();
1145         } catch (SocketTimeoutException ste) {
1146         }
1147     }
1148
1149     public void mapRegisterWithoutMapNotify() {
1150         cleanUP();
1151         sendPacket(mapRegisterPacketWithoutNotify);
1152         try {
1153             receivePacket(3000);
1154             // If didn't timeout then fail:
1155             fail();
1156         } catch (SocketTimeoutException ste) {
1157         }
1158     }
1159
1160     public void registerQueryRegisterWithSmr() throws SocketTimeoutException {
1161         cleanUP();
1162         lms.setShouldUseSmr(true);
1163         mapService.addAuthenticationKey(LispAddressUtil.asIpv4PrefixBinaryEid("153.16.254.1/32"), NULL_AUTH_KEY);
1164         sleepForSeconds(1);
1165
1166         sendPacket(mapRegisterPacketWithNotify);
1167         receiveMapNotify();
1168
1169         sleepForSeconds(1);
1170         sendPacket(mapRequestPacket);
1171         sleepForSeconds(1);
1172
1173         mapRegisterPacketWithoutNotify[mapRegisterPacketWithoutNotify.length - 1] += 1;
1174         sendPacket(mapRegisterPacketWithoutNotify);
1175
1176         ByteBuffer readBuf = ByteBuffer.wrap(receivePacket().getData());
1177         MapRequest smr = MapRequestSerializer.getInstance().deserialize(readBuf, null);
1178         assertTrue(smr.isSmr());
1179         Eid sourceEid = smr.getSourceEid().getEid();
1180         assertTrue(LispAddressUtil.asIpv4Eid("153.16.254.1").equals(sourceEid));
1181         Eid smrEid = smr.getEidItem().get(0).getEid();
1182         assertTrue(LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32").equals(smrEid));
1183     }
1184
1185     // --------------------- Northbound Tests ---------------------------
1186 /*
1187     private void northboundAddKey() throws Exception {
1188         cleanUP();
1189         LispIpv4Address address = LispAddressUtil.asIPAfiAddress("1.2.3.4");
1190         int mask = 32;
1191         String pass = "asdf";
1192
1193         URL url = createPutURL("key");
1194         String authKeyJSON = createAuthKeyJSON(pass, address, mask);
1195         callURL("PUT", "application/json", "text/plain", authKeyJSON, url);
1196
1197         String retrievedKey = lms.getAuthenticationKey(LispAddressUtil.toContainer(address), mask);
1198
1199         // Check stored password matches the one sent
1200         assertEquals(pass, retrievedKey);
1201
1202     }
1203
1204     private void northboundRetrieveSourceDestKey() throws Exception {
1205         cleanUP();
1206         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1207                 address1 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1208                 .primitiveaddress.Ipv4) LispAddressUtil
1209                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.1"));
1210         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1211                 address2 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1212                 .primitiveaddress.Ipv4) LispAddressUtil
1213                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.2"));
1214         int mask1 = 32;
1215         int mask2 = 32;
1216         LcafSourceDestAddr sourceDestAddress = new LcafSourceDestAddrBuilder().setAfi(
1217                 AddressFamilyNumberEnum.LCAF.getIanaCode())
1218                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
1219                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(address1).build())
1220                 .setSrcMaskLength((short) mask1)
1221                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(address2).build())
1222                 .setDstMaskLength((short) mask2).build();
1223         String pass = "asdf";
1224
1225         lms.addAuthenticationKey(LispAddressUtil.toContainer(sourceDestAddress), mask1, pass);
1226
1227         // URL url = createGetKeyIPv4URL(address1, mask1);
1228         URL url = createGetKeySourceDestURL(address1.getIpv4Address().getAfi(),
1229                 ((LispIpv4Address) LispAddressUtil.toAFIfromPrimitive(sourceDestAddress.getSrcAddress()
1230                 .getPrimitiveAddress())).getIpv4Address().getValue(), sourceDestAddress.getSrcMaskLength(),
1231                 ((LispIpv4Address) LispAddressUtil.toAFIfromPrimitive(sourceDestAddress.getDstAddress()
1232                 .getPrimitiveAddress())).getIpv4Address().getValue(), sourceDestAddress.getDstMaskLength());
1233         String reply = callURL("GET", null, "application/json", null, url);
1234         JSONTokener jt = new JSONTokener(reply);
1235         JSONObject json = new JSONObject(jt);
1236
1237         // test that the password matches what was we expected.
1238         assertEquals(pass, json.get("key"));
1239
1240     }
1241
1242     private void northboundRetrieveKey() throws Exception {
1243         cleanUP();
1244         LispIpv4Address address = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1245         int mask = 32;
1246         String pass = "asdf";
1247
1248         lms.addAuthenticationKey(LispAddressUtil.toContainer(address), mask, pass);
1249
1250         URL url = createGetKeyIPv4URL(address, mask);
1251         String reply = callURL("GET", null, "application/json", null, url);
1252         JSONTokener jt = new JSONTokener(reply);
1253         JSONObject json = new JSONObject(jt);
1254
1255         // test that the password matches what was we expected.
1256         assertEquals(pass, json.get("key"));
1257
1258     }
1259
1260     private String createAuthKeyJSON(String key, LispIpv4Address address, int mask) {
1261         return "{\"key\" : \"" + key + "\",\"maskLength\" : " + mask + ",\"address\" : " + "{\"ipAddress\" : \""
1262                 + address.getIpv4Address().getValue() + "\",\"afi\" : " + address.getAfi().shortValue() + "}}";
1263     }
1264
1265     private void northboundAddMapping() throws Exception {
1266         cleanUP();
1267         String pass = "asdf";
1268         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1269         int mask = 32;
1270         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1271
1272         // NB add mapping always checks the key
1273         lms.addAuthenticationKey(LispAddressUtil.toContainer(eid), mask, pass);
1274
1275         URL url = createPutURL("mapping");
1276         String mapRegisterJSON = createMapRegisterJSON(pass, eid, mask, rloc);
1277         callURL("PUT", "application/json", "text/plain", mapRegisterJSON, url);
1278
1279         // Retrieve the RLOC from the database
1280         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1281         mapRequestBuilder.setPitr(false);
1282         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1283         mapRequestBuilder.getEidItem().add(
1284                 new EidRecordBuilder().setMask((short) mask).setLispAddressContainer(
1285                 LispAddressUtil.toContainer(eid)).build());
1286         MapReply mapReply = lms.handleMapRequest(mapRequestBuilder.build());
1287
1288         LispIpv4Address retrievedRloc = (LispIpv4Address) LispAddressUtil.toAFI(
1289                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1290                 .getLispAddressContainer());
1291
1292         assertEquals(rloc.getIpv4Address().getValue(), retrievedRloc.getIpv4Address().getValue());
1293
1294     }
1295
1296     private String createMapRegisterJSON(String key, LispIpv4Address eid, int mask, LispIpv4Address rloc) {
1297         String jsonString = "{ " + "\"key\" : \"" + key + "\"," + "\"mapregister\" : " + "{ "
1298                 + "\"proxyMapReply\" : false, "
1299                 + "\"eidToLocatorRecords\" : " + "[ " + "{ " + "\"authoritative\" : true," + "\"prefixGeneric\" : "
1300                 + "{ " + "\"ipAddress\" : \""
1301                 + eid.getIpv4Address().getValue() + "\"," + "\"afi\" : " + eid.getAfi().shortValue() + "},"
1302                 + "\"mapVersion\" : 0,"
1303                 + "\"maskLength\" : " + mask + ", " + "\"action\" : \"NoAction\"," + "\"locators\" : " + "[ " + "{ "
1304                 + "\"multicastPriority\" : 1,"
1305                 + "\"locatorGeneric\" : " + "{ " + "\"ipAddress\" : \"" + rloc.getIpv4Address().getValue() + "\","
1306                 + "\"afi\" : "
1307                 + rloc.getAfi().shortValue() + "}, " + "\"routed\" : true," + "\"multicastWeight\" : 50,"
1308                 + "\"rlocProbed\" : false, "
1309                 + "\"localLocator\" : false, " + "\"priority\" : 1, " + "\"weight\" : 50 " + "} " + "], "
1310                 + "\"recordTtl\" : 100" + "} " + "], "
1311                 + "\"nonce\" : 3," + "\"keyId\" : 0 " + "} " + "}";
1312
1313         return jsonString;
1314     }
1315
1316     private void northboundRetrieveMapping() throws Exception {
1317         cleanUP();
1318         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1319         int mask = 32;
1320         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1321         // Insert mapping in the database
1322         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1323         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1324         etlr.setLispAddressContainer(LispAddressUtil.toContainer(eid));
1325         etlr.setMaskLength((short) mask);
1326         etlr.setRecordTtl(254);
1327         etlr.setAuthoritative(false);
1328         etlr.setAction(Action.NoAction);
1329         LocatorRecordBuilder record = new LocatorRecordBuilder();
1330         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
1331         record.setRouted(true);
1332         record.setRlocProbed(false);
1333         record.setLocalLocator(false);
1334         record.setPriority((short) 1);
1335         record.setWeight((short) 50);
1336         record.setMulticastPriority((short) 1);
1337         record.setMulticastWeight((short) 1);
1338         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1339         etlr.getLocatorRecord().add(record.build());
1340         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1341         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1342         lms.handleMapRegister(mapRegister.build());
1343
1344         // Get mapping using NB interface. No IID used
1345         URL url = createGetMappingIPv4URL(0, eid, mask);
1346         String reply = callURL("GET", null, "application/json", null, url);
1347         JSONTokener jt = new JSONTokener(reply);
1348         JSONObject json = new JSONObject(jt);
1349
1350         // With just one locator, locators is not a JSONArray
1351         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric")
1352                 .getString("ipAddress");
1353
1354         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
1355
1356     }
1357
1358     private void northboundDeleteMapping() throws Exception {
1359         cleanUP();
1360         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1361         int mask = 32;
1362         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1363         // Insert mapping in the database
1364         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1365         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1366         etlr.setLispAddressContainer(LispAddressUtil.toContainer(eid));
1367         etlr.setMaskLength((short) mask);
1368         etlr.setRecordTtl(254);
1369         etlr.setAuthoritative(false);
1370         etlr.setAction(Action.NoAction);
1371         LocatorRecordBuilder record = new LocatorRecordBuilder();
1372         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
1373         record.setRouted(true);
1374         record.setRlocProbed(false);
1375         record.setLocalLocator(false);
1376         record.setPriority((short) 1);
1377         record.setWeight((short) 50);
1378         record.setMulticastPriority((short) 1);
1379         record.setMulticastWeight((short) 1);
1380         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1381         etlr.getLocatorRecord().add(record.build());
1382         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1383         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1384         lms.handleMapRegister(mapRegister.build());
1385
1386         // Delete mapping using NB interface. No IID used
1387         URL url = createDeleteMappingIPv4URL(0, eid, mask);
1388         String reply = callURL("DELETE", null, "application/json", null, url);
1389
1390         // Get mapping using NB interface. No IID used
1391         url = createGetMappingIPv4URL(0, eid, mask);
1392         reply = callURL("GET", null, "application/json", null, url);
1393         JSONTokener jt = new JSONTokener(reply);
1394         JSONObject json = new JSONObject(jt);
1395
1396         // With just one locator, locators is not a JSONArray
1397         assertEquals(json.getJSONArray("locators").length(), 0);
1398     }
1399
1400     private void northboundRetrieveSourceDestMapping() throws Exception {
1401         cleanUP();
1402         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1403                 address1 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1404                 .primitiveaddress.Ipv4) LispAddressUtil
1405                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.1"));
1406         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1407                 address2 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1408                 .primitiveaddress.Ipv4) LispAddressUtil
1409                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.2"));
1410         int mask1 = 32;
1411         int mask2 = 32;
1412         LcafSourceDestAddr sourceDestAddress = new LcafSourceDestAddrBuilder().setAfi(
1413                 AddressFamilyNumberEnum.LCAF.getIanaCode())
1414                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
1415                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(
1416                         address1).build()).setSrcMaskLength((short) mask1)
1417                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(
1418                         address2).build()).setDstMaskLength((short) mask2).build();
1419         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1420
1421         // Insert mapping in the database
1422         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1423         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1424         etlr.setLispAddressContainer(LispAddressUtil.toContainer(sourceDestAddress));
1425         etlr.setMaskLength((short) mask1);
1426         etlr.setRecordTtl(254);
1427         etlr.setAuthoritative(false);
1428         etlr.setAction(Action.NoAction);
1429         LocatorRecordBuilder record = new LocatorRecordBuilder();
1430         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
1431         record.setRouted(true);
1432         record.setRlocProbed(false);
1433         record.setLocalLocator(false);
1434         record.setPriority((short) 1);
1435         record.setWeight((short) 50);
1436         record.setMulticastPriority((short) 1);
1437         record.setMulticastWeight((short) 1);
1438         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1439         etlr.getLocatorRecord().add(record.build());
1440         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1441         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1442         lms.handleMapRegister(mapRegister.build());
1443
1444         // Get mapping using NB interface. No IID used
1445         URL url = createGetMappingSourceDestURL(address1.getIpv4Address().getAfi(),
1446                 address1.getIpv4Address().getIpv4Address().getValue(),
1447                 mask1,
1448                 address2.getIpv4Address().getIpv4Address().getValue(),
1449                 mask2);
1450         String reply = callURL("GET", null, "application/json", null, url);
1451         JSONTokener jt = new JSONTokener(reply);
1452         JSONObject json = new JSONObject(jt);
1453
1454         // With just one locator, locators is not a JSONArray
1455         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric")
1456         .getString("ipAddress");
1457
1458         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
1459
1460     }
1461
1462     private URL createGetKeyIPv4URL(LispIpv4Address address, int mask) throws MalformedURLException {
1463         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d", "key",
1464                 address.getAfi().shortValue(),
1465                 address.getIpv4Address().getValue(), mask);
1466         URL url = new URL(restUrl);
1467         return url;
1468     }
1469
1470     private URL createGetKeySourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask)
1471             throws MalformedURLException {
1472         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d",
1473                 "key", afi, srcAddress, srcMask,
1474                 dstAddress, dstMask);
1475         URL url = new URL(restUrl);
1476         return url;
1477     }
1478
1479     private URL createGetMappingSourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask)
1480             throws MalformedURLException {
1481         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d",
1482                 "mapping", afi, srcAddress,
1483                 srcMask, dstAddress, dstMask);
1484         URL url = new URL(restUrl);
1485         return url;
1486     }
1487
1488     private URL createGetMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
1489         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping",
1490                 iid, address.getAfi()
1491                 .shortValue(), address.getIpv4Address().getValue(), mask);
1492         URL url = new URL(restUrl);
1493         return url;
1494     }
1495
1496     private URL createDeleteMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
1497         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping",
1498                 iid, address.getAfi()
1499                 .shortValue(), address.getIpv4Address().getValue(), mask);
1500         URL url = new URL(restUrl);
1501         return url;
1502     }
1503
1504     private URL createPutURL(String resource) throws MalformedURLException {
1505
1506         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s", resource);
1507
1508         URL url = new URL(restUrl);
1509         return url;
1510     }
1511
1512     private String createAuthenticationString() {
1513         String authString = "admin:admin";
1514         byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
1515         String authStringEnc = new String(authEncBytes);
1516         return authStringEnc;
1517     }
1518
1519     private String callURL(String method, String content, String accept, String body, URL url) throws IOException,
1520             JSONException {
1521         String authStringEnc = createAuthenticationString();
1522         connection = (HttpURLConnection) url.openConnection();
1523         connection.setRequestMethod(method);
1524         connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
1525         if (content != null) {
1526             connection.setRequestProperty("Content-Type", content);
1527         }
1528         if (accept != null) {
1529             connection.setRequestProperty("Accept", accept);
1530         }
1531         if (body != null) {
1532             // now add the request body
1533             connection.setDoOutput(true);
1534             OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
1535             wr.write(body);
1536             wr.flush();
1537         }
1538         connection.connect();
1539
1540         // getting the result, first check response code
1541         Integer httpResponseCode = connection.getResponseCode();
1542
1543         if (httpResponseCode > 299) {
1544             LOG.trace("HTTP Address: " + url);
1545             LOG.trace("HTTP Response Code: " + httpResponseCode);
1546             fail();
1547         }
1548
1549         InputStream is = connection.getInputStream();
1550         BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
1551         StringBuilder sb = new StringBuilder();
1552         int cp;
1553         while ((cp = rd.read()) != -1) {
1554             sb.append((char) cp);
1555         }
1556         is.close();
1557         connection.disconnect();
1558         return (sb.toString());
1559     }
1560
1561     // timePeriod - in ms
1562     public void assertNoPacketReceived(int timePeriod) {
1563         try {
1564             receivePacket(timePeriod);
1565             // If didn't timeout then fail:
1566             fail();
1567         } catch (SocketTimeoutException ste) {
1568         }
1569     }
1570 */
1571     // ------------------------------- Mask Tests ---------------------------
1572
1573     public void eidPrefixLookupIPv4() throws SocketTimeoutException {
1574         cleanUP();
1575         runPrefixTest(LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/16"),
1576                 LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.2/32"),
1577                 LispAddressUtil.asIpv4PrefixBinaryEid("1.1.1.1/32"));
1578     }
1579
1580     public void eidPrefixLookupIPv6() throws SocketTimeoutException {
1581         cleanUP();
1582         runPrefixTest(LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:4:5:6:7:8/64"),
1583                 LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:4:5:1:2:3/128"),
1584                 LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:1:2:3:1:2/128"));
1585     }
1586
1587     private void runPrefixTest(Eid registerEID, Eid matchedAddress, Eid unMatchedAddress)
1588             throws SocketTimeoutException {
1589         mapService.addAuthenticationKey(registerEID, NULL_AUTH_KEY);
1590         sleepForSeconds(1);
1591
1592         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1593         mapRegister.setWantMapNotify(true);
1594         mapRegister.setNonce((long) 8);
1595         mapRegister.setWantMapNotify(true);
1596         mapRegister.setKeyId((short) 0);
1597         mapRegister.setAuthenticationData(new byte[0]);
1598         mapRegister.setNonce((long) 8);
1599         mapRegister.setProxyMapReply(false);
1600         MappingRecordBuilder etlr = new MappingRecordBuilder();
1601         etlr.setRecordTtl(254);
1602         etlr.setAction(Action.NoAction);
1603         etlr.setAuthoritative(false);
1604         etlr.setMapVersion((short) 0);
1605         etlr.setEid(registerEID);
1606         etlr.setRecordTtl(254);
1607         LocatorRecordBuilder record = new LocatorRecordBuilder();
1608         record.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
1609         record.setLocalLocator(false);
1610         record.setRlocProbed(false);
1611         record.setRouted(true);
1612         record.setMulticastPriority((short) 0);
1613         record.setMulticastWeight((short) 0);
1614         record.setPriority((short) 0);
1615         record.setWeight((short) 0);
1616         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1617         etlr.getLocatorRecord().add(record.build());
1618         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1619         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1620         sendMapRegister(mapRegister.build());
1621         MapNotify mapNotify = receiveMapNotify();
1622         assertEquals(8, mapNotify.getNonce().longValue());
1623         sleepForSeconds(1);
1624         MapRequestBuilder mapRequest = new MapRequestBuilder();
1625         mapRequest.setNonce((long) 4);
1626         mapRequest.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress)).build());
1627         mapRequest.setEidItem(new ArrayList<EidItem>());
1628         mapRequest.setAuthoritative(false);
1629         mapRequest.setMapDataPresent(false);
1630         mapRequest.setPitr(false);
1631         mapRequest.setProbe(false);
1632         mapRequest.setSmr(false);
1633         mapRequest.setSmrInvoked(false);
1634         mapRequest.getEidItem().add(new EidItemBuilder().setEid(matchedAddress).build());
1635         mapRequest.setItrRloc(new ArrayList<ItrRloc>());
1636         mapRequest.getItrRloc().add(
1637                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1638         sendMapRequest(mapRequest.build());
1639         MapReply mapReply = receiveMapReply();
1640         assertEquals(4, mapReply.getNonce().longValue());
1641         assertEquals(record.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
1642                 .get(0).getRloc());
1643         mapRequest.setEidItem(new ArrayList<EidItem>());
1644         mapRequest.getEidItem().add(new EidItemBuilder().setEid(unMatchedAddress).build());
1645         sendMapRequest(mapRequest.build());
1646         mapReply = receiveMapReply();
1647         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1648     }
1649 /*
1650     // This registers an IP with a MapRegister, then adds a password via the
1651     // northbound REST API
1652     // and checks that the password works
1653     public void testPasswordExactMatch() throws Exception {
1654         cleanUP();
1655         String ipString = "10.0.0.1";
1656         LispIpv4Address address = LispAddressUtil.asIPAfiAddress(ipString);
1657         int mask = 32;
1658         String pass = "pass";
1659
1660         URL url = createPutURL("key");
1661
1662         String jsonAuthData = createAuthKeyJSON(pass, address, mask);
1663
1664         LOG.trace("Sending this JSON to LISP server: \n" + jsonAuthData);
1665         LOG.trace("Address: " + address);
1666
1667         byte[] expectedSha = new byte[] { (byte) 146, (byte) 234, (byte) 52, (byte) 247, (byte) 186, (byte) 232,
1668                 (byte) 31, (byte) 249, (byte) 87,
1669                 (byte) 73, (byte) 234, (byte) 54, (byte) 225, (byte) 160, (byte) 129, (byte) 251, (byte) 73, (byte) 53,
1670                 (byte) 196, (byte) 62 };
1671
1672         byte[] zeros = new byte[20];
1673
1674         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
1675
1676         // build a MapRegister
1677         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1678         mapRegister.setWantMapNotify(true);
1679         mapRegister.setNonce((long) 8);
1680         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1681         etlr.setLispAddressContainer(LispAddressUtil.toContainer(address));
1682         etlr.setMaskLength((short) mask);
1683         etlr.setRecordTtl(254);
1684         LocatorRecordBuilder record = new LocatorRecordBuilder();
1685         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1686         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1687         etlr.getLocatorRecord().add(record.build());
1688         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1689         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1690
1691         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
1692         mapRegister.setAuthenticationData(zeros);
1693
1694         sendMapRegister(mapRegister.build());
1695         assertNoPacketReceived(3000);
1696
1697         mapRegister.setAuthenticationData(expectedSha);
1698
1699         sendMapRegister(mapRegister.build());
1700
1701         assertMapNotifyReceived();
1702     }
1703
1704     public void testPasswordMaskMatch() throws Exception {
1705         cleanUP();
1706         LispIpv4Address addressInRange = LispAddressUtil.asIPAfiAddress("10.20.30.40");
1707         LispIpv4Address addressOutOfRange = LispAddressUtil.asIPAfiAddress("20.40.30.40");
1708         LispIpv4Address range = LispAddressUtil.asIPAfiAddress("10.20.30.0");
1709
1710         int mask = 32;
1711         String pass = "pass";
1712
1713         URL url = createPutURL("key");
1714         String jsonAuthData = createAuthKeyJSON(pass, range, 8);
1715
1716         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
1717         // build a MapRegister
1718         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1719
1720         mapRegister.setWantMapNotify(true);
1721         mapRegister.setNonce((long) 8);
1722         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1723         etlr.setLispAddressContainer(LispAddressUtil.toContainer(addressInRange));
1724         etlr.setMaskLength((short) mask);
1725         etlr.setRecordTtl(254);
1726         LocatorRecordBuilder record = new LocatorRecordBuilder();
1727         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1728         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1729         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1730         etlr.getLocatorRecord().add(record.build());
1731         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1732         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1733
1734         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
1735         mapRegister
1736                 .setAuthenticationData(new byte[] { -15, -52, 38, -94, 125, -111, -68, -79, 68, 6, 101, 45, -1, 47, -4,
1737                 -67, -113, 104, -110, -71 });
1738
1739         sendMapRegister(mapRegister.build());
1740
1741         assertMapNotifyReceived();
1742
1743         etlr.setLispAddressContainer(LispAddressUtil.toContainer(addressOutOfRange));
1744         mapRegister
1745                 .setAuthenticationData(new byte[] { -54, 68, -58, -91, -23, 22, -88, -31, 113, 39, 115, 78, -68, -123,
1746                 -71, -14, -99, 67, -23, -73 });
1747
1748         sendMapRegister(mapRegister.build());
1749         assertNoPacketReceived(3000);
1750     }
1751 */
1752     // takes an address, packs it in a MapRegister and sends it
1753     private void registerAddress(Eid eid) throws SocketTimeoutException {
1754         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1755         sleepForSeconds(1);
1756         MapRegisterBuilder mapRegisterBuilder = new MapRegisterBuilder();
1757         mapRegisterBuilder.setWantMapNotify(true);
1758         mapRegisterBuilder.setKeyId((short) 0);
1759         mapRegisterBuilder.setAuthenticationData(new byte[0]);
1760         mapRegisterBuilder.setNonce((long) 8);
1761         mapRegisterBuilder.setProxyMapReply(false);
1762         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1763         etlrBuilder.setEid(eid);
1764         etlrBuilder.setRecordTtl(254);
1765         etlrBuilder.setAction(Action.NoAction);
1766         etlrBuilder.setAuthoritative(false);
1767         etlrBuilder.setMapVersion((short) 0);
1768         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1769         recordBuilder.setLocalLocator(false);
1770         recordBuilder.setRlocProbed(false);
1771         recordBuilder.setRouted(true);
1772         recordBuilder.setMulticastPriority((short) 0);
1773         recordBuilder.setMulticastWeight((short) 0);
1774         recordBuilder.setPriority((short) 0);
1775         recordBuilder.setWeight((short) 0);
1776         recordBuilder.setRloc(locatorEid);
1777         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1778         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1779         mapRegisterBuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1780         mapRegisterBuilder.getMappingRecordItem().add(
1781                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
1782         sendMapRegister(mapRegisterBuilder.build());
1783         MapNotify mapNotify = receiveMapNotify();
1784         assertEquals(8, mapNotify.getNonce().longValue());
1785     }
1786
1787     private MapReply queryForAddress(Eid eid, String srcEid) throws SocketTimeoutException {
1788         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1789         mapRequestBuilder.setNonce((long) 4);
1790         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1791         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1792         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1793         if (srcEid != null) {
1794             mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(srcEid)).build());
1795         } else {
1796             mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress))
1797                     .build());
1798         }
1799         mapRequestBuilder.getItrRloc().add(
1800                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1801         mapRequestBuilder.setAuthoritative(false);
1802         mapRequestBuilder.setMapDataPresent(false);
1803         mapRequestBuilder.setPitr(false);
1804         mapRequestBuilder.setProbe(false);
1805         mapRequestBuilder.setSmr(false);
1806         mapRequestBuilder.setSmrInvoked(false);
1807         sendMapRequest(mapRequestBuilder.build());
1808         return receiveMapReply();
1809     }
1810
1811     // takes an address, packs it in a MapRegister, sends it, returns the
1812     // MapReply
1813     private MapReply registerAddressAndQuery(Eid eid) throws SocketTimeoutException {
1814         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1815         sleepForSeconds(1);
1816         MapRegisterBuilder mapRegisterBuilder = new MapRegisterBuilder();
1817         mapRegisterBuilder.setWantMapNotify(true);
1818         mapRegisterBuilder.setKeyId((short) 0);
1819         mapRegisterBuilder.setAuthenticationData(new byte[0]);
1820         mapRegisterBuilder.setNonce((long) 8);
1821         mapRegisterBuilder.setProxyMapReply(false);
1822         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1823         etlrBuilder.setEid(eid);
1824         etlrBuilder.setRecordTtl(254);
1825         etlrBuilder.setAction(Action.NoAction);
1826         etlrBuilder.setAuthoritative(false);
1827         etlrBuilder.setMapVersion((short) 0);
1828         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1829         recordBuilder.setLocalLocator(false);
1830         recordBuilder.setRlocProbed(false);
1831         recordBuilder.setRouted(true);
1832         recordBuilder.setMulticastPriority((short) 0);
1833         recordBuilder.setMulticastWeight((short) 0);
1834         recordBuilder.setPriority((short) 0);
1835         recordBuilder.setWeight((short) 0);
1836         recordBuilder.setRloc(locatorEid);
1837         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1838         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1839         mapRegisterBuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1840         mapRegisterBuilder.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(
1841                 etlrBuilder.build()).build());
1842         sendMapRegister(mapRegisterBuilder.build());
1843         MapNotify mapNotify = receiveMapNotify();
1844         assertEquals(8, mapNotify.getNonce().longValue());
1845         // wait for the notifications to propagate
1846         sleepForSeconds(1);
1847         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1848         mapRequestBuilder.setNonce((long) 4);
1849         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1850         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1851         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1852         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress)).build());
1853         mapRequestBuilder.getItrRloc().add(
1854                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1855         mapRequestBuilder.setAuthoritative(false);
1856         mapRequestBuilder.setMapDataPresent(false);
1857         mapRequestBuilder.setPitr(false);
1858         mapRequestBuilder.setProbe(false);
1859         mapRequestBuilder.setSmr(false);
1860         mapRequestBuilder.setSmrInvoked(false);
1861         sendMapRequest(mapRequestBuilder.build());
1862         return receiveMapReply();
1863     }
1864
1865     // ------------------------------- LCAF Tests ---------------------------
1866
1867     public void registerAndQuery__SrcDestLCAF() throws SocketTimeoutException {
1868         cleanUP();
1869         String ipPrefix = "10.20.30.200/32";
1870         String macString = "01:02:03:04:05:06";
1871
1872         SourceDestKeyBuilder builder = new SourceDestKeyBuilder();
1873         builder.setSource(new SimpleAddress(new IpPrefix(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1874                 .ietf.inet.types.rev130715.Ipv4Prefix(ipPrefix))));
1875         builder.setDest(new SimpleAddress(new MacAddress(macString)));
1876
1877         EidBuilder eb = new EidBuilder();
1878         eb.setAddressType(SourceDestKeyLcaf.class);
1879         eb.setVirtualNetworkId(null);
1880         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1881                 .lisp.address.address.SourceDestKeyBuilder().setSourceDestKey(builder.build()).build());
1882
1883         MapReply reply = registerAddressAndQuery(eb.build());
1884
1885         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1886         assertEquals(SourceDestKeyLcaf.class, fromNetwork.getAddressType());
1887         SourceDestKey sourceDestFromNetwork = (SourceDestKey) fromNetwork.getAddress();
1888
1889         SimpleAddress receivedAddr1 = sourceDestFromNetwork.getSourceDestKey().getSource();
1890         SimpleAddress receivedAddr2 = sourceDestFromNetwork.getSourceDestKey().getDest();
1891
1892         assertNotNull(receivedAddr1.getIpPrefix().getIpv4Prefix());
1893         assertNotNull(receivedAddr2.getMacAddress());
1894
1895         IpPrefix receivedIP = receivedAddr1.getIpPrefix();
1896         MacAddress receivedMAC = receivedAddr2.getMacAddress();
1897
1898         assertEquals(ipPrefix, receivedIP.getIpv4Prefix().getValue());
1899         assertEquals(macString, receivedMAC.getValue());
1900     }
1901
1902     public void registerAndQuery__SrcDestLCAFOverlap() throws SocketTimeoutException {
1903         cleanUP();
1904         String ipString1 = "10.10.10.0";
1905         String ipString2 = "20.20.20.0";
1906         String ipPrefix1 = ipString1 + "/24";
1907         String ipPrefix2 = ipString2 + "/24";
1908
1909         Eid srcDst = LispAddressUtil.asSrcDstEid(ipString1, ipString2, 24, 24, 0);
1910         registerAddress(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2));
1911         registerAddress(srcDst);
1912
1913         // exact match
1914         MapReply reply = queryForAddress(srcDst, null);
1915
1916         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1917         assertEquals(SourceDestKeyLcaf.class, fromNetwork.getAddressType());
1918         SourceDestKey sourceDestFromNetwork = (SourceDestKey) fromNetwork.getAddress();
1919
1920         IpPrefix receivedAddr1 = sourceDestFromNetwork.getSourceDestKey().getSource().getIpPrefix();
1921         IpPrefix receivedAddr2 = sourceDestFromNetwork.getSourceDestKey().getDest().getIpPrefix();
1922
1923         assertNotNull(receivedAddr1.getIpv4Prefix());
1924         assertNotNull(receivedAddr2.getIpv4Prefix());
1925
1926         assertEquals(ipPrefix1, receivedAddr1.getIpv4Prefix().getValue());
1927         assertEquals(ipPrefix2, receivedAddr2.getIpv4Prefix().getValue());
1928
1929         // srcEid/dstEid match
1930         reply = queryForAddress(LispAddressUtil.asIpv4PrefixBinaryEid("20.20.20.1/32"), "10.10.10.1");
1931         fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1932         assertEquals(Ipv4PrefixBinaryAfi.class, fromNetwork.getAddressType());
1933
1934         assertEquals(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2), fromNetwork);
1935
1936         // dstEid match only
1937         reply = queryForAddress(LispAddressUtil.asIpv4PrefixBinaryEid("20.20.20.1/32"), "1.2.3.4");
1938         fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1939         assertEquals(Ipv4PrefixBinaryAfi.class, fromNetwork.getAddressType());
1940
1941         assertEquals(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2), fromNetwork);
1942     }
1943
1944     public void registerAndQuery__KeyValueLCAF() throws SocketTimeoutException {
1945         cleanUP();
1946         String ipString = "10.20.30.200";
1947         String macString = "01:02:03:04:05:06";
1948         SimpleAddress addrToSend1 = new SimpleAddress(new IpAddress(new Ipv4Address(ipString)));
1949         SimpleAddress addrToSend2 = new SimpleAddress(new MacAddress(macString));
1950         Eid kv = LispAddressUtil.asKeyValueAddressEid(addrToSend1, addrToSend2);
1951
1952         MapReply reply = registerAddressAndQuery(kv);
1953
1954         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1955         assertEquals(KeyValueAddressLcaf.class, fromNetwork.getAddressType());
1956         KeyValueAddress keyValueFromNetwork = (KeyValueAddress) fromNetwork.getAddress();
1957
1958         SimpleAddress receivedAddr1 = keyValueFromNetwork.getKeyValueAddress().getKey();
1959         SimpleAddress receivedAddr2 = keyValueFromNetwork.getKeyValueAddress().getValue();
1960
1961         assertNotNull(receivedAddr1.getIpAddress().getIpv4Address());
1962         assertNotNull(receivedAddr2.getMacAddress());
1963
1964         Ipv4Address receivedIP = receivedAddr1.getIpAddress().getIpv4Address();
1965         MacAddress receivedMAC = receivedAddr2.getMacAddress();
1966
1967         assertEquals(ipString, receivedIP.getValue());
1968         assertEquals(macString, receivedMAC.getValue());
1969     }
1970
1971     public void registerAndQuery__ListLCAF() throws SocketTimeoutException {
1972         cleanUP();
1973         String macString = "01:02:03:04:05:06";
1974         String ipString = "10.20.255.30";
1975         List<SimpleAddress> addresses = new ArrayList<SimpleAddress>();
1976         addresses.add(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
1977         addresses.add(new SimpleAddress(new MacAddress(macString)));
1978         AfiListBuilder listbuilder = new AfiListBuilder();
1979         listbuilder.setAddressList(addresses);
1980
1981         EidBuilder eb = new EidBuilder();
1982         eb.setAddressType(AfiListLcaf.class);
1983         eb.setVirtualNetworkId(null);
1984         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1985                 .lisp.address.address.AfiListBuilder().setAfiList(listbuilder.build()).build());
1986
1987         MapReply reply = registerAddressAndQuery(eb.build());
1988
1989         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1990
1991         assertEquals(AfiListLcaf.class, receivedAddress.getAddressType());
1992
1993         AfiList listAddrFromNetwork = (AfiList) receivedAddress.getAddress();
1994         SimpleAddress receivedAddr1 = (SimpleAddress) listAddrFromNetwork.getAfiList().getAddressList().get(0);
1995         SimpleAddress receivedAddr2 = (SimpleAddress) listAddrFromNetwork.getAfiList().getAddressList().get(1);
1996
1997         assertNotNull(receivedAddr1.getIpAddress().getIpv4Address());
1998         assertNotNull(receivedAddr2.getMacAddress());
1999
2000         assertEquals(macString, receivedAddr2.getMacAddress().getValue());
2001         assertEquals(ipString, receivedAddr1.getIpAddress().getIpv4Address().getValue());
2002     }
2003
2004     public void registerAndQuery__SegmentLCAF() throws SocketTimeoutException {
2005         cleanUP();
2006         String ipString = "10.20.255.30";
2007         int instanceId = 6;
2008
2009         EidBuilder eb = new EidBuilder();
2010         eb.setAddressType(Ipv4PrefixAfi.class);
2011         eb.setVirtualNetworkId(new InstanceIdType((long) instanceId));
2012         eb.setAddress(new Ipv4PrefixBuilder().setIpv4Prefix(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns
2013                 .yang.ietf.inet.types.rev130715.Ipv4Prefix(ipString)).build());
2014
2015         MapReply reply = registerAddressAndQuery(eb.build());
2016
2017         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2018         assertEquals(Ipv4PrefixAfi.class, receivedAddress.getAddressType());
2019
2020         assertEquals(ipString, ((Ipv4Prefix) receivedAddress.getAddress()).getIpv4Prefix().getValue());
2021
2022         assertEquals(instanceId, receivedAddress.getVirtualNetworkId().getValue().intValue());
2023     }
2024
2025     public void registerAndQuery__TrafficEngineering() throws SocketTimeoutException {
2026         cleanUP();
2027         String macString = "01:02:03:04:05:06";
2028         String ipString = "10.20.255.30";
2029         HopBuilder hopBuilder = new HopBuilder();
2030         hopBuilder.setAddress(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
2031         hopBuilder.setLrsBits(new LrsBits(true, false, true));
2032         Hop hop1 = hopBuilder.build();
2033         hopBuilder.setAddress(new SimpleAddress(new MacAddress(macString)));
2034         hopBuilder.setLrsBits(new LrsBits(false, true, false));
2035         Hop hop2 = hopBuilder.build();
2036         ExplicitLocatorPathBuilder elpBuilder = new ExplicitLocatorPathBuilder();
2037         elpBuilder.setHop(new ArrayList<Hop>());
2038         elpBuilder.getHop().add(hop1);
2039         elpBuilder.getHop().add(hop2);
2040
2041         EidBuilder eb = new EidBuilder();
2042         eb.setAddressType(ExplicitLocatorPathLcaf.class);
2043         eb.setVirtualNetworkId(null);
2044         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2045                 .lisp.address.address.ExplicitLocatorPathBuilder().setExplicitLocatorPath(elpBuilder.build()).build());
2046
2047         MapReply reply = registerAddressAndQuery(eb.build());
2048
2049         assertEquals(ExplicitLocatorPathLcaf.class, reply.getMappingRecordItem().get(0).getMappingRecord().getEid()
2050                 .getAddressType());
2051
2052         ExplicitLocatorPath receivedAddress = (ExplicitLocatorPath) reply.getMappingRecordItem().get(0)
2053                 .getMappingRecord().getEid().getAddress();
2054
2055         Hop receivedHop1 = (Hop) receivedAddress.getExplicitLocatorPath().getHop().get(0);
2056         Hop receivedHop2 = (Hop) receivedAddress.getExplicitLocatorPath().getHop().get(1);
2057
2058         assertEquals(true, receivedHop1.getLrsBits().isLookup());
2059         assertEquals(false, receivedHop1.getLrsBits().isRlocProbe());
2060         assertEquals(true, receivedHop1.getLrsBits().isStrict());
2061
2062         assertEquals(false, receivedHop2.getLrsBits().isLookup());
2063         assertEquals(true, receivedHop2.getLrsBits().isRlocProbe());
2064         assertEquals(false, receivedHop2.getLrsBits().isStrict());
2065
2066         assertNotNull(receivedHop1.getAddress().getIpAddress().getIpv4Address());
2067         assertNotNull(receivedHop2.getAddress().getMacAddress());
2068
2069         assertEquals(ipString, receivedHop1.getAddress().getIpAddress().getIpv4Address().getValue());
2070         assertEquals(macString, receivedHop2.getAddress().getMacAddress().getValue());
2071     }
2072
2073     public void registerAndQuery__ApplicationData() throws SocketTimeoutException {
2074         cleanUP();
2075         String ipString = "1.2.3.4";
2076         short protocol = 1;
2077         int ipTOs = 2;
2078         int localPortLow = 3;
2079         int localPortHigh = 4;
2080         int remotePortLow = 4;
2081         int remotePortHigh = 5;
2082
2083         ApplicationDataBuilder builder = new ApplicationDataBuilder();
2084         builder.setIpTos(ipTOs);
2085         builder.setProtocol(protocol);
2086         builder.setLocalPortLow(new PortNumber(localPortLow));
2087         builder.setLocalPortHigh(new PortNumber(localPortHigh));
2088         builder.setRemotePortLow(new PortNumber(remotePortLow));
2089         builder.setRemotePortHigh(new PortNumber(remotePortHigh));
2090         builder.setAddress(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
2091
2092         EidBuilder eb = new EidBuilder();
2093         eb.setAddressType(ApplicationDataLcaf.class);
2094         eb.setVirtualNetworkId(null);
2095         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2096                 .lisp.address.address.ApplicationDataBuilder().setApplicationData(builder.build()).build());
2097         Eid addressToSend = eb.build();
2098
2099         MapReply reply = registerAddressAndQuery(addressToSend);
2100
2101         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2102
2103         assertEquals(ApplicationDataLcaf.class, receivedAddress.getAddressType());
2104
2105         ApplicationData receivedApplicationDataAddress = (ApplicationData) receivedAddress.getAddress();
2106         assertEquals(protocol, receivedApplicationDataAddress.getApplicationData().getProtocol().intValue());
2107         assertEquals(ipTOs, receivedApplicationDataAddress.getApplicationData().getIpTos().intValue());
2108         assertEquals(localPortLow, receivedApplicationDataAddress.getApplicationData().getLocalPortLow().getValue()
2109                 .intValue());
2110         assertEquals(localPortHigh, receivedApplicationDataAddress.getApplicationData().getLocalPortHigh().getValue()
2111                 .intValue());
2112         assertEquals(remotePortLow, receivedApplicationDataAddress.getApplicationData().getRemotePortLow().getValue()
2113                 .intValue());
2114         assertEquals(remotePortHigh, receivedApplicationDataAddress.getApplicationData().getRemotePortHigh().getValue()
2115                 .intValue());
2116
2117         SimpleAddress ipAddressReceived = receivedApplicationDataAddress.getApplicationData().getAddress();
2118         assertEquals(ipString, ipAddressReceived.getIpAddress().getIpv4Address().getValue());
2119     }
2120
2121     // ------------------- TimeOut Tests -----------
2122
2123     public void mapRequestMapRegisterAndMapRequestTestTimeout() throws SocketTimeoutException {
2124         cleanUP();
2125         ConfigIni.getInstance().setSmrRetryCount(0);
2126         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
2127         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
2128         sleepForSeconds(1);
2129         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
2130         mapRequestBuilder.setNonce((long) 4);
2131         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
2132         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
2133         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
2134         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
2135         mapRequestBuilder.getItrRloc().add(
2136                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
2137
2138         sendMapRequest(mapRequestBuilder.build());
2139         MapReply mapReply = receiveMapReply();
2140         assertEquals(4, mapReply.getNonce().longValue());
2141         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
2142
2143         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
2144         mapRegisterbuilder.setWantMapNotify(true);
2145         mapRegisterbuilder.setNonce((long) 8);
2146
2147         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
2148         etlrBuilder.setEid(eid);
2149         etlrBuilder.setRecordTtl(254);
2150
2151         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
2152         recordBuilder.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
2153         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
2154         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
2155         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2156         mapRegisterbuilder.getMappingRecordItem().add(
2157                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
2158
2159         sendMapRegister(mapRegisterbuilder.build());
2160         MapNotify mapNotify = receiveMapNotify();
2161         assertEquals(8, mapNotify.getNonce().longValue());
2162         sleepForSeconds(1);
2163
2164         sendMapRequest(mapRequestBuilder.build());
2165         mapReply = receiveMapReply();
2166         assertEquals(4, mapReply.getNonce().longValue());
2167         assertEquals(recordBuilder.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord()
2168                 .getLocatorRecord().get(0).getRloc());
2169
2170         causeEntryToBeCleaned();
2171         sendMapRequest(mapRequestBuilder.build());
2172         mapReply = receiveMapReply();
2173         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
2174     }
2175
2176     public void mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse() throws Exception {
2177         cleanUP();
2178         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
2179         MapRequest mapRequest = createMapRequest(eid);
2180
2181         testTTLBeforeRegister(mapRequest);
2182
2183         registerForTTL(eid);
2184
2185         testTTLAfterRegister(mapRequest);
2186
2187         causeEntryToBeCleaned();
2188         testTTLAfterClean(mapRequest);
2189
2190         //northboundAddKey();
2191         //testTTLAfterAutherize(mapRequest);
2192
2193     }
2194
2195     private void timedOutMappingRecord() {
2196         cleanUP();
2197         mapService.setMappingMerge(true);
2198         // mapping expires after 1 second
2199         ConfigIni.getInstance().setRegistrationValiditySb(1000L);
2200
2201         final Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32", new InstanceIdType(10L));
2202         final XtrId xtrId = new XtrId(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});
2203         final SiteId siteId = new SiteId(new byte[]{1, 2, 3, 4, 5, 6, 7, 8});
2204
2205         final LocatorRecord locatorRecord = new LocatorRecordBuilder()
2206                 .setRloc(LispAddressUtil.asIpv4Rloc("1.1.1.1")).setLocatorId("locator-id").build();
2207         final MappingRecord mappingRecord = new MappingRecordBuilder()
2208                 .setEid(eid)
2209                 .setSiteId(siteId)
2210                 .setRecordTtl(1000)
2211                 .setXtrId(xtrId)
2212                 .setAction(Action.NoAction)
2213                 .setAuthoritative(true)
2214                 .setLocatorRecord(Lists.newArrayList()).build();
2215         mappingRecord.getLocatorRecord().add(locatorRecord);
2216
2217         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
2218         mapService.addMapping(MappingOrigin.Southbound, eid, siteId,
2219                 new MappingData(MappingOrigin.Southbound, mappingRecord, System.currentTimeMillis()));
2220         sleepForSeconds(2);
2221
2222         MappingRecord resultRecord = (MappingRecord) mapService.getMapping(MappingOrigin.Southbound, eid);
2223         assertNull(resultRecord);
2224     }
2225
2226     private void testTTLAfterClean(MapRequest mapRequest) throws SocketTimeoutException {
2227         MapReply mapReply;
2228         sendMapRequest(mapRequest);
2229         mapReply = receiveMapReply();
2230         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
2231     }
2232
2233     private void causeEntryToBeCleaned() {
2234         // TODO XXX for the time being, to keep master and stable/lithium in sync, we need to remove the forceful
2235         // expiration of DAO entries. Once we're past this, we'll have to expose methods to setTimeUnit(TimeUnit)
2236         // and cleanOld() (expired) entries in IFlowMapping (and perhaps ILispDAO) and use them here.
2237         mapService.cleanCachedMappings();
2238     }
2239
2240     private void testTTLAfterRegister(MapRequest mapRequest) throws SocketTimeoutException {
2241         MapReply mapReply;
2242         sendMapRequest(mapRequest);
2243         mapReply = receiveMapReply();
2244         assertEquals(LispAddressUtil.asIpv4Rloc("4.3.2.1"), mapReply.getMappingRecordItem().get(0).getMappingRecord()
2245                 .getLocatorRecord().get(0).getRloc());
2246         assertCorrectMapReplyTTLAndAction(mapReply, 254, Action.NoAction);
2247     }
2248
2249     private void registerForTTL(Eid eid) throws SocketTimeoutException {
2250         MapRegister mapRegister = createMapRegister(eid);
2251         sendMapRegister(mapRegister);
2252         assertMapNotifyReceived();
2253     }
2254
2255     private void testTTLBeforeRegister(MapRequest mapRequest) throws SocketTimeoutException {
2256         MapReply mapReply;
2257         sendMapRequest(mapRequest);
2258         mapReply = receiveMapReply();
2259         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
2260     }
2261 /*
2262     private void testTTLAfterAutherize(MapRequest mapRequest) throws SocketTimeoutException {
2263         MapReply mapReply;
2264         sendMapRequest(mapRequest);
2265         mapReply = receiveMapReply();
2266         assertCorrectMapReplyTTLAndAction(mapReply, 1, Action.NativelyForward);
2267     }
2268 */
2269     private void assertCorrectMapReplyTTLAndAction(MapReply mapReply, int expectedTTL, Action expectedAction) {
2270         assertEquals(expectedTTL, mapReply.getMappingRecordItem().get(0).getMappingRecord().getRecordTtl().intValue());
2271         assertEquals(expectedAction, mapReply.getMappingRecordItem().get(0).getMappingRecord().getAction());
2272     }
2273
2274     private MapRegister createMapRegister(Eid eid, Rloc rloc) {
2275         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
2276         mapRegisterbuilder.setWantMapNotify(true);
2277         mapRegisterbuilder.setNonce((long) 8);
2278         mapRegisterbuilder.setKeyId((short) 0);
2279         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
2280         etlrBuilder.setEid(eid);
2281         etlrBuilder.setRecordTtl(254);
2282         etlrBuilder.setAuthoritative(false);
2283         etlrBuilder.setAction(Action.NoAction);
2284         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
2285         recordBuilder.setRloc(rloc);
2286         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
2287         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
2288         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2289         mapRegisterbuilder.getMappingRecordItem().add(
2290                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
2291         MapRegister mapRegister = mapRegisterbuilder.build();
2292         return mapRegister;
2293     }
2294
2295     private MapRegister createMapRegister(Eid eid) {
2296         return createMapRegister(eid, LispAddressUtil.asIpv4Rloc("4.3.2.1"));
2297     }
2298
2299     private MapRequest createMapRequest(Eid eid) {
2300         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
2301         mapRequestBuilder.setNonce((long) 4);
2302         mapRequestBuilder.setPitr(false);
2303         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
2304         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
2305         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
2306         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
2307         mapRequestBuilder.getItrRloc().add(
2308                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
2309         MapRequest mr = mapRequestBuilder.build();
2310         return mr;
2311     }
2312
2313     public void testSimpleNonProxy() throws SocketTimeoutException, SocketException {
2314         cleanUP();
2315         String rloc = "127.0.0.3";
2316         int port = LispMessage.PORT_NUM;
2317         Rloc ipRloc = LispAddressUtil.asIpv4Rloc(rloc);
2318         sendProxyMapRequest(rloc, port, ipRloc);
2319
2320     }
2321
2322     public void testNonProxyOtherPort() throws SocketTimeoutException, SocketException {
2323         cleanUP();
2324         String rloc = "127.0.0.3";
2325         int port = 4350;
2326
2327         RlocBuilder rb = new RlocBuilder();
2328         rb.setAddressType(ApplicationDataLcaf.class);
2329         rb.setVirtualNetworkId(null);
2330         rb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2331                 .lisp.address.address.ApplicationDataBuilder()
2332                 .setApplicationData(new ApplicationDataBuilder().setAddress(new SimpleAddress(new IpAddress(
2333                 new Ipv4Address(rloc)))).setLocalPortLow(new PortNumber(port)).build()).build());
2334         Rloc adLcaf = rb.build();
2335
2336         LOG.info("testNonProxyOtherPort:" + LispAddressStringifier.getString(adLcaf));
2337         sendProxyMapRequest(rloc, port, adLcaf);
2338
2339     }
2340
2341     private class XtrRequestMappingListener implements OdlLispProtoListener {
2342
2343         @Override
2344         public void onGotMapReply(GotMapReply notification) {
2345         }
2346
2347         @Override
2348         public void onAddMapping(AddMapping notification) {
2349         }
2350
2351         @Override
2352         public void onXtrReplyMapping(XtrReplyMapping notification) {
2353         }
2354
2355         @Override
2356         public void onRequestMapping(RequestMapping notification) {
2357         }
2358
2359         @Override
2360         public void onGotMapNotify(GotMapNotify notification) {
2361         }
2362
2363         @Override
2364         public void onXtrRequestMapping(XtrRequestMapping notification) {
2365         }
2366
2367         @Override
2368         public void onMappingKeepAlive(MappingKeepAlive notification) {
2369         }
2370
2371     }
2372
2373     public void testRecievingNonProxyOnXtrPort() throws SocketTimeoutException, SocketException, Throwable {
2374         cleanUP();
2375         configLispPlugin.shouldListenOnXtrPort(true);
2376         notificationCalled = false;
2377         final String eid = "10.10.10.10/32";
2378         String rloc = "127.0.0.3";
2379         int port = LispMessage.XTR_PORT_NUM;
2380
2381         RlocBuilder rb = new RlocBuilder();
2382         rb.setAddressType(ApplicationDataLcaf.class);
2383         rb.setVirtualNetworkId(null);
2384         rb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2385                 .lisp.address.address.ApplicationDataBuilder()
2386                 .setApplicationData(new ApplicationDataBuilder().setAddress(new SimpleAddress(new IpAddress(
2387                 new Ipv4Address(rloc)))).setLocalPortLow(new PortNumber(port)).build()).build());
2388         Rloc adLcaf = rb.build();
2389
2390         final MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
2391         ((LispMappingService) lms).getNotificationService().registerNotificationListener(
2392                 new XtrRequestMappingListener() {
2393
2394             @Override
2395             public void onXtrRequestMapping(XtrRequestMapping notification) {
2396                 assertEquals(((Ipv4Prefix) mapRequest.getEidItem().get(0).getEid().getAddress())
2397                         .getIpv4Prefix().getValue(), eid);
2398                 notificationCalled = true;
2399                 LOG.warn("notification arrived");
2400             }
2401         });
2402         sendMapRequest(mapRequest, port);
2403         for (int i = 0; i < MAX_NOTIFICATION_RETRYS; i++) {
2404             if (notificationCalled) {
2405                 return;
2406             } else {
2407                 LOG.warn("notification hasn't arrived, sleeping...");
2408                 Thread.sleep(500);
2409             }
2410         }
2411
2412         fail("Notification hasn't arrived");
2413
2414     }
2415
2416     private void sendProxyMapRequest(String rloc, int port, Rloc adLcaf) throws SocketTimeoutException,
2417             SocketException {
2418         String eid = "10.1.0.1/32";
2419         MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
2420         sendMapRequest(mapRequest);
2421         DatagramSocket nonProxySocket = new DatagramSocket(new InetSocketAddress(rloc, port));
2422         MapRequest receivedMapRequest = receiveMapRequest(nonProxySocket);
2423         assertEquals(mapRequest.getNonce(), receivedMapRequest.getNonce());
2424         assertEquals(mapRequest.getSourceEid(), receivedMapRequest.getSourceEid());
2425         assertEquals(mapRequest.getItrRloc(), receivedMapRequest.getItrRloc());
2426         assertEquals(mapRequest.getEidItem(), receivedMapRequest.getEidItem());
2427         nonProxySocket.close();
2428     }
2429
2430     private MapRequest createNonProxyMapRequest(String eid, Rloc adLcaf) throws SocketTimeoutException {
2431         MapRegister mr = createMapRegister(LispAddressUtil.asIpv4PrefixBinaryEid(eid));
2432         LocatorRecord record = new LocatorRecordBuilder(mr.getMappingRecordItem().get(0).getMappingRecord()
2433                 .getLocatorRecord().get(0)).setRloc(adLcaf).build();
2434         mr.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().set(0, record);
2435         sendMapRegister(mr);
2436         assertMapNotifyReceived();
2437         MapRequest mapRequest = createMapRequest(LispAddressUtil.asIpv4PrefixBinaryEid(eid));
2438         MapRequestBuilder builder = new MapRequestBuilder(mapRequest);
2439         builder.setPitr(true);
2440         mapRequest = builder.build();
2441         return mapRequest;
2442     }
2443
2444     private void assertMapNotifyReceived() throws SocketTimeoutException {
2445         receiveMapNotify();
2446     }
2447
2448     private MapReply receiveMapReply() throws SocketTimeoutException {
2449         return receiveMapReply(socket, 1000);
2450     }
2451
2452     private MapRequest receiveMapRequest(DatagramSocket datagramSocket) throws SocketTimeoutException {
2453         return MapRequestSerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket(
2454                 datagramSocket, 30000).getData()), null);
2455     }
2456
2457     private MapNotify receiveMapNotify() throws SocketTimeoutException {
2458         return MapNotifySerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket().getData()));
2459     }
2460
2461     private void sendMapRequest(MapRequest mapRequest) {
2462         sendMapRequest(mapRequest, LispMessage.PORT_NUM);
2463     }
2464
2465     private void sendMapRequest(MapRequest mapRequest, int port) {
2466         sendPacket(MapRequestSerializer.getInstance().serialize(mapRequest).array(), port);
2467     }
2468
2469     private void sendMapRegister(MapRegister mapRegister) {
2470         sendPacket(MapRegisterSerializer.getInstance().serialize(mapRegister).array());
2471     }
2472
2473     private void sendPacket(byte[] bytesToSend) {
2474         sendPacket(bytesToSend, LispMessage.PORT_NUM);
2475     }
2476
2477     private void sendPacket(byte[] bytesToSend, int port) {
2478         try {
2479             DatagramPacket packet = new DatagramPacket(bytesToSend, bytesToSend.length);
2480             initPacketAddress(packet, port);
2481             LOG.trace("Sending packet to LispPlugin on socket, port {}", port);
2482             socket.send(packet);
2483         } catch (Throwable t) {
2484             fail();
2485         }
2486     }
2487
2488     private DatagramPacket receivePacket() throws SocketTimeoutException {
2489         return receivePacket(6000);
2490     }
2491
2492     private DatagramPacket receivePacket(int timeout) throws SocketTimeoutException {
2493         return receivePacket(socket, timeout);
2494     }
2495
2496     private DatagramPacket receivePacket(DatagramSocket receivedSocket, int timeout) throws SocketTimeoutException {
2497         try {
2498             byte[] buffer = new byte[4096];
2499             DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
2500             LOG.trace("Waiting for packet from socket...");
2501             receivedSocket.setSoTimeout(timeout);
2502             receivedSocket.receive(receivePacket);
2503             LOG.trace("Received packet from socket!");
2504             return receivePacket;
2505         } catch (SocketTimeoutException ste) {
2506             throw ste;
2507         } catch (Throwable t) {
2508             fail();
2509             return null;
2510         }
2511     }
2512
2513     private MapReply receiveMapReply(DatagramSocket receivedSocket, int timeout) throws SocketTimeoutException {
2514         DatagramPacket packet;
2515         try {
2516             while (true) {
2517                 packet = receivePacket(receivedSocket, timeout);
2518                 final ByteBuffer buff = ByteBuffer.wrap(packet.getData());
2519                 final int type = ByteUtil.getUnsignedByte(buff, LispMessage.Pos.TYPE) >> 4;
2520                 final Object lispType = MessageType.forValue(type);
2521
2522                 if (lispType == MessageType.MapReply) {
2523                     return MapReplySerializer.getInstance().deserialize(buff);
2524                 }
2525             }
2526         } catch (SocketTimeoutException ste) {
2527             throw ste;
2528         }
2529     }
2530
2531     private void sleepForSeconds(int seconds) {
2532         try {
2533             Thread.sleep(seconds*1000);
2534         } catch (InterruptedException e) {
2535             LOG.warn("Interrupted while sleeping", e);
2536         }
2537     }
2538
2539     private void sleepForMilliseconds(long milliseconds) {
2540         try {
2541             Thread.sleep(milliseconds);
2542         } catch (InterruptedException e) {
2543             LOG.warn("Interrupted while sleeping", e);
2544         }
2545     }
2546
2547     private void initPacketAddress(DatagramPacket packet, int port) throws UnknownHostException {
2548         packet.setAddress(InetAddress.getByName(lispBindAddress));
2549         packet.setPort(port);
2550     }
2551
2552     private DatagramSocket initSocket(DatagramSocket socket, int port) {
2553         for (int i=0; i < NUM_OF_ATTEMPTS_TO_CREATE_SOCKET; i++) {
2554             try {
2555                 LOG.debug("Binding socket on {}:{}", ourAddress, port);
2556                 return new DatagramSocket(new InetSocketAddress(ourAddress, port));
2557             } catch (SocketException e) {
2558                 LOG.error("Can't initialize socket for {}:{}", ourAddress, port, e);
2559             }
2560         }
2561         fail();
2562         return null;
2563     }
2564
2565     private byte[] extractWSUdpByteArray(String wiresharkHex) {
2566         final int HEADER_LEN = 42;
2567         byte[] res = new byte[1000];
2568         String[] split = wiresharkHex.split(" ");
2569         int counter = 0;
2570         for (String cur : split) {
2571             cur = cur.trim();
2572             if (cur.length() == 2) {
2573                 ++counter;
2574                 if (counter > HEADER_LEN) {
2575                     res[counter - HEADER_LEN - 1] = (byte) Integer.parseInt(cur, 16);
2576                 }
2577
2578             }
2579         }
2580         return Arrays.copyOf(res, counter - HEADER_LEN);
2581     }
2582
2583     private String stateToString(int state) {
2584         switch (state) {
2585         case Bundle.ACTIVE:
2586             return "ACTIVE";
2587         case Bundle.INSTALLED:
2588             return "INSTALLED";
2589         case Bundle.RESOLVED:
2590             return "RESOLVED";
2591         case Bundle.UNINSTALLED:
2592             return "UNINSTALLED";
2593         default:
2594             return "Not CONVERTED";
2595         }
2596     }
2597
2598     private void areWeReady() throws InvalidSyntaxException {
2599         sleepForSeconds(5);
2600
2601         assertNotNull(bc);
2602         boolean debugit = false;
2603         Bundle b[] = bc.getBundles();
2604         for (Bundle element : b) {
2605             int state = element.getState();
2606             LOG.trace("Bundle[" + element.getBundleId() + "]:" + element.getSymbolicName() + ",v"
2607                     + element.getVersion() + ", state:" + stateToString(state));
2608             if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
2609                 LOG.debug("Bundle:" + element.getSymbolicName() + " state:" + stateToString(state));
2610
2611                 // try {
2612                 // String host = element.getHeaders().get("FRAGMENT-HOST");
2613                 // if (host != null) {
2614                 // LOG.warn("Bundle " + element.getSymbolicName() +
2615                 // " is a fragment which is part of: " + host);
2616                 // LOG.warn("Required imports are: " +
2617                 // element.getHeaders().get("IMPORT-PACKAGE"));
2618                 // } else {
2619                 // element.start();
2620                 // }
2621                 // } catch (BundleException e) {
2622                 // LOG.error("BundleException:", e);
2623                 // fail();
2624                 // }
2625
2626                 debugit = true;
2627
2628             }
2629         }
2630         if (debugit) {
2631             LOG.warn(("Do some debugging because some bundle is unresolved"));
2632         }
2633         // assertNotNull(broker);
2634
2635         configLispPlugin.setLispAddress(lispBindAddress);
2636
2637         // Uncomment this code to Know which services were actually loaded to
2638         // BundleContext
2639
2640         /*
2641         for (ServiceReference sr : bc.getAllServiceReferences(null, null)) {
2642             LOG.info(sr.getBundle().getSymbolicName());
2643             LOG.info(sr.toString());
2644         }
2645         */
2646
2647         sleepForSeconds(1);
2648     }
2649
2650     private void cleanUP() {
2651         after();
2652         mapService.cleanCachedMappings();
2653         configLispPlugin.shouldListenOnXtrPort(false);
2654         socket = initSocket(socket, LispMessage.PORT_NUM);
2655
2656     }
2657
2658     private void restartSocket() {
2659         after();
2660         socket = initSocket(socket, LispMessage.PORT_NUM);
2661     }
2662
2663 }