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