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