Updated LISP NB to latest ODL NB conventions. Added exception handling.
[lispflowmapping.git] / mappingservice / integrationtest / src / test / java / org / opendaylight / lispflowmapping / integrationtest / MappingServiceIntegrationTest.java
1 package org.opendaylight.lispflowmapping.integrationtest;
2
3 import static org.junit.Assert.assertArrayEquals;
4 import static org.junit.Assert.assertEquals;
5 import static org.junit.Assert.assertNotNull;
6 import static org.junit.Assert.assertTrue;
7 import static org.junit.Assert.fail;
8 import static org.ops4j.pax.exam.CoreOptions.junitBundles;
9 import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
10 import static org.ops4j.pax.exam.CoreOptions.options;
11 import static org.ops4j.pax.exam.CoreOptions.systemPackages;
12 import static org.ops4j.pax.exam.CoreOptions.systemProperty;
13
14 import java.io.BufferedReader;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.InputStreamReader;
18 import java.io.OutputStreamWriter;
19 import java.net.DatagramPacket;
20 import java.net.DatagramSocket;
21 import java.net.HttpURLConnection;
22 import java.net.InetAddress;
23 import java.net.InetSocketAddress;
24 import java.net.MalformedURLException;
25 import java.net.SocketException;
26 import java.net.SocketTimeoutException;
27 import java.net.URL;
28 import java.net.UnknownHostException;
29 import java.nio.ByteBuffer;
30 import java.nio.charset.Charset;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.List;
34
35 import javax.inject.Inject;
36
37 import org.apache.commons.codec.binary.Base64;
38 import org.codehaus.jettison.json.JSONException;
39 import org.codehaus.jettison.json.JSONObject;
40 import org.codehaus.jettison.json.JSONTokener;
41 import org.junit.After;
42 import org.junit.Before;
43 import org.junit.Test;
44 import org.junit.runner.RunWith;
45 import org.opendaylight.lispflowmapping.implementation.serializer.LispMessage;
46 import org.opendaylight.lispflowmapping.implementation.serializer.MapNotifySerializer;
47 import org.opendaylight.lispflowmapping.implementation.serializer.MapRegisterSerializer;
48 import org.opendaylight.lispflowmapping.implementation.serializer.MapReplySerializer;
49 import org.opendaylight.lispflowmapping.implementation.serializer.MapRequestSerializer;
50 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMapping;
51 import org.opendaylight.lispflowmapping.type.lisp.EidRecord;
52 import org.opendaylight.lispflowmapping.type.lisp.EidToLocatorRecord;
53 import org.opendaylight.lispflowmapping.type.lisp.LocatorRecord;
54 import org.opendaylight.lispflowmapping.type.lisp.MapNotify;
55 import org.opendaylight.lispflowmapping.type.lisp.MapRegister;
56 import org.opendaylight.lispflowmapping.type.lisp.MapReply;
57 import org.opendaylight.lispflowmapping.type.lisp.MapRequest;
58 import org.opendaylight.lispflowmapping.type.lisp.address.LispAddress;
59 import org.opendaylight.lispflowmapping.type.lisp.address.LispApplicationDataLCAFAddress;
60 import org.opendaylight.lispflowmapping.type.lisp.address.LispDistinguishedNameAddress;
61 import org.opendaylight.lispflowmapping.type.lisp.address.LispIpv4Address;
62 import org.opendaylight.lispflowmapping.type.lisp.address.LispIpv6Address;
63 import org.opendaylight.lispflowmapping.type.lisp.address.LispLCAFAddress;
64 import org.opendaylight.lispflowmapping.type.lisp.address.LispListLCAFAddress;
65 import org.opendaylight.lispflowmapping.type.lisp.address.LispMACAddress;
66 import org.opendaylight.lispflowmapping.type.lisp.address.LispSegmentLCAFAddress;
67 import org.opendaylight.lispflowmapping.type.lisp.address.LispSourceDestLCAFAddress;
68 import org.opendaylight.lispflowmapping.type.lisp.address.LispTrafficEngineeringLCAFAddress;
69 import org.opendaylight.lispflowmapping.type.lisp.address.ReencapHop;
70 import org.ops4j.pax.exam.Option;
71 import org.ops4j.pax.exam.junit.Configuration;
72 import org.ops4j.pax.exam.junit.PaxExam;
73 import org.ops4j.pax.exam.util.PathUtils;
74 import org.osgi.framework.Bundle;
75 import org.osgi.framework.BundleContext;
76 import org.osgi.framework.InvalidSyntaxException;
77 import org.osgi.framework.ServiceReference;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80
81 @RunWith(PaxExam.class)
82 public class MappingServiceIntegrationTest {
83
84     private IFlowMapping lms;
85     protected static final Logger logger = LoggerFactory.getLogger(MappingServiceIntegrationTest.class);
86     private byte[] mapRequestPacket;
87     private byte[] mapRegisterPacketWithNotify;
88     private byte[] mapRegisterPacketWithoutNotify;
89     int lispPortNumber = LispMessage.PORT_NUM;
90     String lispBindAddress = "127.0.0.1";
91     String ourAddress = "127.0.0.2";
92     private DatagramSocket socket;
93     private byte[] mapRegisterPacketWithAuthenticationAndMapNotify;
94     private byte[] mapRegisterPacketWithNotifyWithListLCAFAndDistinguishedName;
95
96     public static final String ODL = "org.opendaylight.controller";
97     public static final String YANG = "org.opendaylight.yangtools";
98     public static final String JERSEY = "com.sun.jersey";
99
100     @After
101     public void after() {
102         if (socket != null) {
103             socket.close();
104         }
105         if (connection != null) {
106             connection.disconnect();
107         }
108     }
109
110     @Before
111     public void before() throws Exception {
112         socket = initSocket(socket);
113         // mapResolver = context.mock(IMapResolver.class);
114         // mapServer = context.mock(IMapServer.class);
115
116         // SRC: 127.0.0.1:58560 to 127.0.0.1:4342
117         // LISP(Type = 8 - Encapsulated)
118         // IP: 192.168.136.10 -> 1.2.3.4
119         // UDP: 56756
120         // LISP(Type = 1 Map-Request
121         // Record Count: 1
122         // ITR-RLOC count: 0
123         // Source EID AFI: 0
124         // Source EID not present
125         // Nonce: 0x3d8d2acd39c8d608
126         // ITR-RLOC AFI=1 Address=192.168.136.10
127         // Record 1: 1.2.3.4/32
128         mapRequestPacket = extractWSUdpByteArray(new String("0000   00 00 00 00 00 00 00 00 00 00 00 00 08 00 45 00 " //
129                 + "0010   00 58 00 00 40 00 40 11 3c 93 7f 00 00 01 7f 00 "
130                 + "0020   00 01 e4 c0 10 f6 00 44 fe 57 80 00 00 00 45 00 "
131                 + "0030   00 38 d4 31 00 00 ff 11 56 f3 7f 00 00 02 01 02 "
132                 + "0040   03 04 dd b4 10 f6 00 24 ef 3a 10 00 00 01 3d 8d "
133                 + "0050   2a cd 39 c8 d6 08 00 00 00 01 7f 00 00 02 00 20 " //
134                 + "0060   00 01 01 02 03 04"));
135
136         // IP: 192.168.136.10 -> 128.223.156.35
137         // UDP: 49289 -> 4342
138         // LISP(Type = 3 Map-Register, P=1, M=1
139         // Record Counter: 1
140         // Nonce: 0
141         // Key ID: 0x0001
142         // AuthDataLength: 20 Data:
143         // e8:f5:0b:c5:c5:f2:b0:21:27:a8:21:41:04:f3:46:5a:a5:68:89:ec
144         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
145         // No-Action
146         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
147         // Priority/Weight: 1/100, Multicast Priority/Weight:
148         // 255/0
149         //
150
151         mapRegisterPacketWithAuthenticationAndMapNotify = extractWSUdpByteArray(new String("0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
152                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
153                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
154                 + "0030   00 00 00 00 00 00 00 01 00 14 0e a4 c6 d8 a4 06 "
155                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
156                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
157                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
158
159         // IP: 192.168.136.10 -> 128.223.156.35
160         // UDP: 49289 -> 4342
161         // LISP(Type = 3 Map-Register, P=1, M=1
162         // Record Counter: 1
163         // Nonce: 7
164         // Key ID: 0x0000 NO AUTHENTICATION!!
165         // AuthDataLength: 00 Data:
166         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
167         // No-Action
168         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
169         // Priority/Weight: 1/100, Multicast Priority/Weight:
170         // 255/0
171         //
172
173         mapRegisterPacketWithNotify = extractWSUdpByteArray(new String("0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
174                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
175                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
176                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
177                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
178                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
179                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
180
181         // IP: 192.168.136.10 -> 128.223.156.35
182         // UDP: 49289 -> 4342
183         // LISP(Type = 3 Map-Register, P=1, M=1
184         // Record Counter: 1
185         // Nonce: 7
186         // Key ID: 0x0000 NO AUTHENTICATION!!
187         // AuthDataLength: 00 Data:
188         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
189         // No-Action
190         // LIST LCAF
191         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
192         // Local RLOC: Distinguished Name("david"), Reachable,
193         // Priority/Weight: 1/100, Multicast Priority/Weight:
194         // 255/0
195         //
196
197         mapRegisterPacketWithNotifyWithListLCAFAndDistinguishedName = extractWSUdpByteArray(new String(
198                 "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
199                         + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
200                         + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
201                         + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
202                         + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
203                         + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
204                         + "0060   ff 00 00 05 40 03 00 00 01 00 00 16 00 01 c0 a8 " //
205                         + "0070   88 0a 40 03 00 00 01 00 00 08 00 11 64 61 76 69 " //
206                         + "0080   64 00"));
207
208         // IP: 192.168.136.10 -> 128.223.156.35
209         // UDP: 49289 -> 4342
210         // LISP(Type = 3 Map-Register, P=1, M=1
211         // Record Counter: 1
212         // Nonce: 7
213         // Key ID: 0x0000 NO AUTHENTICATION!!
214         // AuthDataLength: 00 Data:
215         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
216         // No-Action
217         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
218         // Priority/Weight: 1/100, Multicast Priority/Weight:
219         // 255/0
220         //
221
222         mapRegisterPacketWithoutNotify = extractWSUdpByteArray(new String("0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
223                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
224                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 00 01 00 00 "
225                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
226                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
227                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
228                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
229     }
230
231     @Inject
232     private BundleContext bc;
233     private HttpURLConnection connection;
234
235     // Configure the OSGi container
236     @Configuration
237     public Option[] config() {
238         return options(
239                 //
240                 systemProperty("logback.configurationFile").value("file:" + PathUtils.getBaseDir() + "/src/test/resources/logback.xml"),
241                 // To start OSGi console for inspection remotely
242                 systemProperty("osgi.console").value("2401"),
243                 systemProperty("org.eclipse.gemini.web.tomcat.config.path").value(PathUtils.getBaseDir() + "/src/test/resources/tomcat-server.xml"),
244
245                 // setting default level. Jersey bundles will need to be started
246                 // earlier.
247                 systemProperty("osgi.bundles.defaultStartLevel").value("4"),
248
249                 // Set the systemPackages (used by clustering)
250                 systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc", "javax.crypto", "javax.crypto.spec"),
251
252                 // OSGI infra
253                 mavenBundle("org.jboss.spec.javax.transaction", "jboss-transaction-api_1.1_spec").versionAsInProject(),
254                 mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(),
255                 mavenBundle("org.apache.felix", "org.apache.felix.dependencymanager").versionAsInProject(),
256
257                 // List logger bundles
258                 mavenBundle("org.slf4j", "jcl-over-slf4j").versionAsInProject(),
259                 mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(),
260                 mavenBundle("org.slf4j", "log4j-over-slf4j").versionAsInProject(),
261                 mavenBundle("ch.qos.logback", "logback-core").versionAsInProject(),
262                 mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject(),
263
264                 mavenBundle(ODL, "config-api").versionAsInProject(), //
265                 mavenBundle(ODL, "config-manager").versionAsInProject(), //
266                 mavenBundle("commons-io", "commons-io").versionAsInProject(),
267
268                 mavenBundle("commons-fileupload", "commons-fileupload").versionAsInProject(),
269
270                 mavenBundle("equinoxSDK381", "javax.servlet").versionAsInProject(),
271                 mavenBundle("equinoxSDK381", "javax.servlet.jsp").versionAsInProject(),
272                 mavenBundle("equinoxSDK381", "org.eclipse.equinox.ds").versionAsInProject(),
273
274                 mavenBundle("equinoxSDK381", "org.eclipse.equinox.util").versionAsInProject(),
275                 mavenBundle("equinoxSDK381", "org.eclipse.osgi.services").versionAsInProject(),
276                 mavenBundle("equinoxSDK381", "org.apache.felix.gogo.command").versionAsInProject(),
277                 mavenBundle("equinoxSDK381", "org.apache.felix.gogo.runtime").versionAsInProject(),
278                 mavenBundle("equinoxSDK381", "org.apache.felix.gogo.shell").versionAsInProject(),
279                 mavenBundle("equinoxSDK381", "org.eclipse.equinox.cm").versionAsInProject(),
280                 mavenBundle("equinoxSDK381", "org.eclipse.equinox.console").versionAsInProject(),
281                 mavenBundle("equinoxSDK381", "org.eclipse.equinox.launcher").versionAsInProject(),
282
283                 mavenBundle("org.apache.felix", "org.apache.felix.dependencymanager").versionAsInProject(),
284                 mavenBundle("org.apache.felix", "org.apache.felix.dependencymanager.shell").versionAsInProject(),
285
286                 mavenBundle("com.google.code.gson", "gson").versionAsInProject(),
287                 mavenBundle("org.jboss.spec.javax.transaction", "jboss-transaction-api_1.1_spec").versionAsInProject(),
288                 mavenBundle("org.apache.felix", "org.apache.felix.fileinstall").versionAsInProject(),
289                 mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(),
290                 mavenBundle("commons-codec", "commons-codec").versionAsInProject(),
291                 mavenBundle("virgomirror", "org.eclipse.jdt.core.compiler.batch").versionAsInProject(),
292                 mavenBundle("eclipselink", "javax.persistence").versionAsInProject(),
293                 mavenBundle("eclipselink", "javax.resource").versionAsInProject(),
294
295                 mavenBundle("orbit", "javax.activation").versionAsInProject(),
296                 mavenBundle("orbit", "javax.annotation").versionAsInProject(),
297                 mavenBundle("orbit", "javax.ejb").versionAsInProject(),
298                 mavenBundle("orbit", "javax.el").versionAsInProject(),
299                 mavenBundle("orbit", "javax.mail.glassfish").versionAsInProject(),
300                 mavenBundle("orbit", "javax.xml.rpc").versionAsInProject(),
301                 mavenBundle("orbit", "org.apache.catalina").versionAsInProject(),
302
303                 mavenBundle("orbit", "org.apache.catalina.ha").versionAsInProject().noStart(),
304                 mavenBundle("orbit", "org.apache.catalina.tribes").versionAsInProject().noStart(),
305                 mavenBundle("orbit", "org.apache.coyote").versionAsInProject().noStart(),
306                 mavenBundle("orbit", "org.apache.jasper").versionAsInProject().noStart(),
307
308                 mavenBundle("orbit", "org.apache.el").versionAsInProject(),
309                 mavenBundle("orbit", "org.apache.juli.extras").versionAsInProject(),
310                 mavenBundle("orbit", "org.apache.tomcat.api").versionAsInProject(),
311                 mavenBundle("orbit", "org.apache.tomcat.util").versionAsInProject().noStart(),
312                 mavenBundle("orbit", "javax.servlet.jsp.jstl").versionAsInProject(),
313                 mavenBundle("orbit", "javax.servlet.jsp.jstl.impl").versionAsInProject(),
314
315                 // Basic bundles needed
316                 mavenBundle("org.opendaylight.controller", "containermanager").versionAsInProject(),
317                 mavenBundle("org.opendaylight.controller", "containermanager.it.implementation").versionAsInProject(),
318
319                 // Specific bundles
320                 mavenBundle(ODL, "sal-binding-api").versionAsInProject(), //
321                 mavenBundle(ODL, "sal-binding-config").versionAsInProject(),
322                 mavenBundle(ODL, "sal-binding-broker-impl").versionAsInProject(), //
323                 mavenBundle(ODL, "sal-common").versionAsInProject(), //
324                 mavenBundle(ODL, "sal-common-api").versionAsInProject(), //
325                 mavenBundle(ODL, "sal-common-impl").versionAsInProject(),
326                 mavenBundle(ODL, "sal-common-util").versionAsInProject(), //
327
328                 mavenBundle(YANG, "concepts").versionAsInProject(),
329                 mavenBundle(YANG, "yang-binding").versionAsInProject(), //
330                 mavenBundle(YANG, "yang-common").versionAsInProject(), //
331                 mavenBundle(YANG + ".thirdparty", "xtend-lib-osgi").versionAsInProject(),//
332                 mavenBundle(YANG, "yang-data-api").versionAsInProject(), //
333                 mavenBundle(YANG, "yang-data-impl").versionAsInProject(), //
334                 mavenBundle(YANG, "yang-model-api").versionAsInProject(), //
335                 mavenBundle(YANG, "yang-model-api").versionAsInProject(), //
336                 mavenBundle(YANG, "yang-model-util").versionAsInProject(), //
337                 mavenBundle(YANG, "yang-parser-api").versionAsInProject(),
338                 mavenBundle(YANG, "yang-parser-impl").versionAsInProject(),
339                 mavenBundle(YANG, "binding-generator-spi").versionAsInProject(), //
340                 mavenBundle(YANG, "binding-model-api").versionAsInProject(), //
341                 mavenBundle(YANG, "binding-generator-util").versionAsInProject(),
342                 mavenBundle(YANG, "yang-parser-impl").versionAsInProject(),
343                 mavenBundle(YANG, "binding-type-provider").versionAsInProject(),
344                 mavenBundle(YANG, "binding-generator-api").versionAsInProject(),
345                 mavenBundle(YANG, "binding-generator-spi").versionAsInProject(),
346                 mavenBundle(YANG, "binding-generator-impl").versionAsInProject(),
347                 mavenBundle(YANG + ".thirdparty", "antlr4-runtime-osgi-nohead").versionAsInProject(), //
348
349                 mavenBundle("com.google.guava", "guava").versionAsInProject(), //
350                 mavenBundle("org.javassist", "javassist").versionAsInProject(), //
351
352                 // Northbound bundles
353                 mavenBundle("org.opendaylight.controller", "commons.northbound").versionAsInProject(), //
354                 mavenBundle(ODL + ".thirdparty", "com.sun.jersey.jersey-servlet").versionAsInProject(), //
355                 mavenBundle(ODL + ".thirdparty", "net.sf.jung2").versionAsInProject(), //
356                 mavenBundle(ODL + ".thirdparty", "org.apache.catalina.filters.CorsFilter").versionAsInProject().noStart(),
357                 mavenBundle(JERSEY, "jersey-client").versionAsInProject(),
358                 mavenBundle(JERSEY, "jersey-server").versionAsInProject().startLevel(2),
359                 mavenBundle(JERSEY, "jersey-core").versionAsInProject().startLevel(2),
360                 mavenBundle(JERSEY, "jersey-json").versionAsInProject().startLevel(2),
361                 mavenBundle("org.codehaus.jackson", "jackson-mapper-asl").versionAsInProject(),//
362                 mavenBundle("org.codehaus.jackson", "jackson-core-asl").versionAsInProject(),//
363                 mavenBundle("org.codehaus.jackson", "jackson-jaxrs").versionAsInProject(),//
364                 mavenBundle("org.codehaus.jackson", "jackson-xc").versionAsInProject(),//
365                 mavenBundle("org.codehaus.jettison", "jettison").versionAsInProject(),//
366                 mavenBundle("org.ow2.asm", "asm-all").versionAsInProject(), //
367                 mavenBundle("org.opendaylight.controller", "bundlescanner").versionAsInProject(),//
368                 mavenBundle("org.opendaylight.controller", "bundlescanner.implementation").versionAsInProject(),//
369                 mavenBundle("org.opendaylight.controller", "switchmanager").versionAsInProject(),//
370                 mavenBundle("org.opendaylight.controller", "connectionmanager").versionAsInProject(),//
371                 mavenBundle("org.opendaylight.controller", "connectionmanager.implementation").versionAsInProject(),//
372                 mavenBundle("org.opendaylight.controller", "commons.httpclient").versionAsInProject(), //
373                 mavenBundle("org.opendaylight.controller", "configuration").versionAsInProject(),//
374                 mavenBundle("org.opendaylight.controller", "configuration.implementation").versionAsInProject(),//
375                 mavenBundle("org.opendaylight.controller", "usermanager").versionAsInProject(), //
376                 mavenBundle("org.opendaylight.controller", "usermanager.implementation").versionAsInProject(), //
377                 mavenBundle("org.springframework", "org.springframework.asm").versionAsInProject(),
378                 mavenBundle("org.springframework", "org.springframework.aop").versionAsInProject(),
379                 mavenBundle("org.springframework", "org.springframework.context").versionAsInProject(),
380                 mavenBundle("org.springframework", "org.springframework.context.support").versionAsInProject(),
381                 mavenBundle("org.springframework", "org.springframework.core").versionAsInProject(),
382                 mavenBundle("org.springframework", "org.springframework.beans").versionAsInProject(),
383                 mavenBundle("org.springframework", "org.springframework.expression").versionAsInProject(),
384                 mavenBundle("org.springframework", "org.springframework.web").versionAsInProject(),
385
386                 mavenBundle("org.aopalliance", "com.springsource.org.aopalliance").versionAsInProject(),
387                 mavenBundle("org.springframework", "org.springframework.web.servlet").versionAsInProject(),
388                 mavenBundle("org.springframework.security", "spring-security-config").versionAsInProject(),
389                 mavenBundle("org.springframework.security", "spring-security-core").versionAsInProject(),
390                 mavenBundle("org.springframework.security", "spring-security-web").versionAsInProject(),
391                 mavenBundle("org.springframework.security", "spring-security-taglibs").versionAsInProject(),
392                 mavenBundle("org.springframework", "org.springframework.transaction").versionAsInProject(),
393                 mavenBundle("org.opendaylight.controller", "sal.connection").versionAsInProject(),
394                 mavenBundle("org.opendaylight.controller", "sal.connection.implementation").versionAsInProject(),
395                 mavenBundle("org.opendaylight.controller", "security").versionAsInProject().noStart(),
396
397                 // Tomcat for northbound
398                 mavenBundle("geminiweb", "org.eclipse.gemini.web.core").versionAsInProject(),
399                 mavenBundle("geminiweb", "org.eclipse.gemini.web.extender").versionAsInProject(),
400                 mavenBundle("geminiweb", "org.eclipse.gemini.web.tomcat").versionAsInProject(),
401                 mavenBundle("geminiweb", "org.eclipse.virgo.kernel.equinox.extensions").versionAsInProject().noStart(),
402                 mavenBundle("geminiweb", "org.eclipse.virgo.util.common").versionAsInProject(),
403                 mavenBundle("geminiweb", "org.eclipse.virgo.util.io").versionAsInProject(),
404                 mavenBundle("geminiweb", "org.eclipse.virgo.util.math").versionAsInProject(),
405                 mavenBundle("geminiweb", "org.eclipse.virgo.util.osgi").versionAsInProject(),
406                 mavenBundle("geminiweb", "org.eclipse.virgo.util.osgi.manifest").versionAsInProject(),
407                 mavenBundle("geminiweb", "org.eclipse.virgo.util.parser.manifest").versionAsInProject(),
408
409                 // Our bundles
410                 mavenBundle("org.opendaylight.controller", "clustering.stub").versionAsInProject(),
411                 mavenBundle("org.opendaylight.controller", "clustering.services").versionAsInProject(),
412                 mavenBundle("org.opendaylight.controller", "sal").versionAsInProject(),
413                 mavenBundle("org.opendaylight.lispflowmapping", "mappingservice.api").versionAsInProject(),
414                 mavenBundle("org.opendaylight.lispflowmapping", "mappingservice.implementation").versionAsInProject(), //
415                 mavenBundle("org.opendaylight.lispflowmapping", "mappingservice.southbound").versionAsInProject(), //
416                 mavenBundle("org.opendaylight.lispflowmapping", "mappingservice.northbound").versionAsInProject(), //
417
418                 // Additions
419                 mavenBundle(ODL, "sal-core-api").versionAsInProject().update(), //
420                 mavenBundle(ODL, "sal-core-spi").versionAsInProject().update(), //
421                 mavenBundle(ODL, "sal-broker-impl").versionAsInProject(), //
422                 mavenBundle(ODL, "sal-connector-api").versionAsInProject(), //
423                 junitBundles());
424     }
425
426     @Test
427     public void mapRequestSimple() throws SocketTimeoutException {
428         sendPacket(mapRequestPacket);
429         ByteBuffer readBuf = ByteBuffer.wrap(receivePacket().getData());
430         MapReply reply = MapReplySerializer.getInstance().deserialize(readBuf);
431         assertEquals(4435248268955932168L, reply.getNonce());
432
433     }
434
435     @Test
436     public void mapRegisterWithMapNotify() throws SocketTimeoutException {
437         sendPacket(mapRegisterPacketWithNotify);
438         MapNotify reply = recieveMapNotify();
439         assertEquals(7, reply.getNonce());
440     }
441
442     @Test
443     public void northboundAddKey() throws Exception {
444
445         LispIpv4Address address = new LispIpv4Address("10.0.0.1");
446         int mask = 32;
447         String pass = "asdf";
448
449         URL url = createPutURL("key");
450         String authKeyJSON = createAuthKeyJSON(pass, address, mask);
451         callURL("PUT", "application/json", null, authKeyJSON, url);
452
453         String retrievedKey = lms.getAuthenticationKey(address, mask);
454
455         //Check stored password matches the one sent
456         assertEquals(pass, retrievedKey);
457
458     }
459
460     @Test
461     public void northboundRetrieveKey() throws Exception {
462
463         LispIpv4Address address = new LispIpv4Address("10.0.0.1");
464         int mask = 32;
465         String pass = "asdf";
466
467         lms.addAuthenticationKey(address, mask, pass);
468
469         URL url = createGetKeyIPv4URL(address, mask);
470         String reply = callURL("GET", null, "application/json", null, url);
471         JSONTokener jt = new JSONTokener(reply);
472         JSONObject json = new JSONObject(jt);
473
474         // test that the password matches what was we expected.
475         assertEquals(pass, json.get("key"));
476
477     }
478
479     private String createAuthKeyJSON(String key, LispIpv4Address address, int mask) {
480         return "{\"key\" : \"" + key + "\",\"maskLength\" : " + mask + ",\"address\" : " + "{\"ipAddress\" : \""
481                 + address.getAddress().getHostAddress() + "\",\"afi\" : " + address.getAfi().getIanaCode() + "}}";
482     }
483
484     @Test
485     public void northboundAddMapping() throws Exception {
486
487         String pass = "asdf";
488         LispIpv4Address eid = new LispIpv4Address("10.0.0.1");
489         int mask = 32;
490         LispIpv4Address rloc = new LispIpv4Address("20.0.0.2");
491
492         //NB add mapping always checks the key
493         lms.addAuthenticationKey(eid, mask, pass);
494
495         URL url = createPutURL("mapping");
496         String mapRegisterJSON = createMapRegisterJSON(pass, eid, mask, rloc);
497         callURL("PUT", "application/json", null, mapRegisterJSON, url);
498
499         //Retrieve the RLOC from the database
500         MapRequest mapRequest = new MapRequest();
501         mapRequest.addEidRecord(new EidRecord((byte) mask, eid));
502         MapReply mapReply = lms.handleMapRequest(mapRequest);
503
504         LispIpv4Address retrievedRloc = (LispIpv4Address) mapReply.getEidToLocatorRecords().get(0).getLocators().get(0).getLocator();
505
506         assertEquals(rloc.getAddress().getHostAddress(), retrievedRloc.getAddress().getHostAddress());
507
508     }
509
510     private String createMapRegisterJSON(String key, LispIpv4Address eid, int mask, LispIpv4Address rloc) {
511         String jsonString = "{ " + "\"key\" : \"" + key + "\"," + "\"mapregister\" : " + "{ " 
512                 + "\"proxyMapReply\" : false, " + "\"eidToLocatorRecords\" : " + "[ " + "{ " + "\"authoritative\" : true," + "\"prefixGeneric\" : "
513                 + "{ " + "\"ipAddress\" : \"" + eid.getAddress().getHostAddress() + "\"," + "\"afi\" : " + eid.getAfi().getIanaCode() + "},"
514                 + "\"mapVersion\" : 0," + "\"maskLength\" : " + mask + ", " + "\"action\" : \"NoAction\"," + "\"locators\" : " + "[ " + "{ "
515                 + "\"multicastPriority\" : 1," + "\"locatorGeneric\" : " + "{ " + "\"ipAddress\" : \"" + rloc.getAddress().getHostAddress() + "\","
516                 + "\"afi\" : " + rloc.getAfi().getIanaCode() + "}, " + "\"routed\" : true," + "\"multicastWeight\" : 50,"
517                 + "\"rlocProbed\" : false, " + "\"localLocator\" : false, " + "\"priority\" : 1, " + "\"weight\" : 50 " + "} " + "], "
518                 + "\"recordTtl\" : 100" + "} " + "], " + "\"nonce\" : 3," + "\"keyId\" : 0 " + "} " + "}";
519
520         return jsonString;
521     }
522
523     @Test
524     public void northboundRetrieveMapping() throws Exception {
525
526         String pass = "";
527         LispIpv4Address eid = new LispIpv4Address("10.0.0.1");
528         int mask = 32;
529         LispIpv4Address rloc = new LispIpv4Address("20.0.0.2");
530
531         //Insert mapping in the database
532         MapRegister mapRegister = new MapRegister();
533         EidToLocatorRecord etlr = new EidToLocatorRecord();
534         etlr.setPrefix(eid);
535         etlr.setMaskLength(mask);
536         etlr.setRecordTtl(254);
537         LocatorRecord record = new LocatorRecord();
538         record.setLocator(rloc);
539         etlr.addLocator(record);
540         mapRegister.addEidToLocator(etlr);
541         lms.handleMapRegister(mapRegister);
542
543         //Get mapping using NB interface. No IID used
544         URL url = createGetMappingIPv4URL(0, eid, mask);
545         String reply = callURL("GET", null, "application/json", null, url);
546         JSONTokener jt = new JSONTokener(reply);
547         JSONObject json = new JSONObject(jt);
548
549         //With just one locator, locators is not a JSONArray
550         String rlocRetrieved = json.getJSONObject("locators").getJSONObject("locatorGeneric").getString("ipAddress");
551
552         assertEquals(rloc.getAddress().getHostAddress(), rlocRetrieved);
553
554     }
555
556     private URL createGetKeyIPv4URL(LispIpv4Address address, int mask) throws MalformedURLException {
557
558         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%s/%d",
559                         "key",
560                         address.getAfi().getIanaCode(), 
561                         address.getAddress().getHostAddress(), 
562                         mask);
563
564         URL url = new URL(restUrl);
565         return url;
566     }
567
568     private URL createGetMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
569
570         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d",
571                         "mapping",
572                         iid,
573                         address.getAfi().getIanaCode(), 
574                         address.getAddress().getHostAddress(), 
575                         mask);
576
577         URL url = new URL(restUrl);
578         return url;
579     }
580
581     private URL createPutURL(String resource) throws MalformedURLException {
582
583         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s",resource);
584
585         URL url = new URL(restUrl);
586         return url;
587     }
588
589     private String createAuthenticationString() {
590         String authString = "admin:admin";
591         byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
592         String authStringEnc = new String(authEncBytes);
593         return authStringEnc;
594     }
595
596     private String callURL(String method, String content, String accept, String body, URL url) throws IOException, JSONException {
597         String authStringEnc = createAuthenticationString();
598         connection = (HttpURLConnection) url.openConnection();
599         connection.setRequestMethod(method);
600         connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
601         if (content != null) {
602             connection.setRequestProperty("Content-Type", content);
603         }
604         if (accept != null) {
605             connection.setRequestProperty("Accept", accept);
606         }
607         if (body != null) {
608             //now add the request body
609             connection.setDoOutput(true);
610             OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
611             wr.write(body);
612             wr.flush();
613         }
614         connection.connect();
615
616         // getting the result, first check response code
617         Integer httpResponseCode = connection.getResponseCode();
618
619         if (httpResponseCode > 299) {
620             logger.info("HTTP Response Code: " + httpResponseCode);
621             fail();
622         }
623
624         InputStream is = connection.getInputStream();
625         BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
626         StringBuilder sb = new StringBuilder();
627         int cp;
628         while ((cp = rd.read()) != -1) {
629             sb.append((char) cp);
630         }
631         is.close();
632         connection.disconnect();
633         return (sb.toString());
634     }
635
636     private MapReply registerAddressAndQuery(LispAddress eid) throws SocketTimeoutException {
637         return registerAddressAndQuery(eid, -1);
638     }
639
640     private LispAddress locatorEid = new LispIpv4Address("4.3.2.1");
641
642     // takes an address, packs it in a MapRegister, sends it, returns the
643     // MapReply
644     private MapReply registerAddressAndQuery(LispAddress eid, int maskLength) throws SocketTimeoutException {
645         MapRegister mapRegister = new MapRegister();
646         mapRegister.setWantMapNotify(true);
647         mapRegister.setNonce(8);
648         EidToLocatorRecord etlr = new EidToLocatorRecord();
649         etlr.setPrefix(eid);
650         if (maskLength != -1) {
651             etlr.setMaskLength(maskLength);
652         }
653         etlr.setRecordTtl(254);
654         LocatorRecord record = new LocatorRecord();
655         record.setLocator(locatorEid);
656         etlr.addLocator(record);
657         mapRegister.addEidToLocator(etlr);
658         sendMapRegister(mapRegister);
659         MapNotify mapNotify = recieveMapNotify();
660         assertEquals(8, mapNotify.getNonce());
661         MapRequest mapRequest = new MapRequest();
662         mapRequest.setNonce(4);
663         mapRequest.addEidRecord(new EidRecord((byte) 32, eid));
664         mapRequest.addItrRloc(new LispIpv4Address(ourAddress));
665         sendMapRequest(mapRequest);
666         return recieveMapReply();
667     }
668
669     @Test
670     public void mapRegisterWithMapNotifyAndMapRequest() throws SocketTimeoutException {
671
672         LispIpv4Address eid = new LispIpv4Address("1.2.3.4");
673
674         MapReply mapReply = registerAddressAndQuery(eid, 32);
675
676         assertEquals(4, mapReply.getNonce());
677         assertEquals(locatorEid, mapReply.getEidToLocatorRecords().get(0).getLocators().get(0).getLocator());
678
679     }
680
681     @Test
682     public void registerAndQuery__MAC() throws SocketTimeoutException {
683         byte[] macAddress = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5, (byte) 6 };
684
685         LispMACAddress eid = new LispMACAddress(macAddress);
686         MapReply reply = registerAddressAndQuery(eid);
687
688         LispAddress addressFromNetwork = reply.getEidToLocatorRecords().get(0).getPrefix();
689         assertTrue(addressFromNetwork instanceof LispMACAddress);
690         byte[] macAddressFromReply = ((LispMACAddress) addressFromNetwork).getMAC();
691
692         assertArrayEquals(macAddress, macAddressFromReply);
693     }
694
695     @Test
696     public void registerAndQuery__SrcDestLCAF() throws SocketTimeoutException {
697         String ipString = "10.20.30.200";
698         LispAddress addrToSend1 = new LispIpv4Address(ipString);
699         byte[] fakeMAC = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5, (byte) 6 };
700         LispAddress addrToSend2 = new LispMACAddress(fakeMAC);
701         LispLCAFAddress address = new LispSourceDestLCAFAddress((byte) 0, (short) 0, (byte) 32, (byte) 0, addrToSend1, addrToSend2);
702
703         MapReply reply = registerAddressAndQuery(address);
704
705         LispAddress fromNetwork = reply.getEidToLocatorRecords().get(0).getPrefix();
706         assertTrue(fromNetwork instanceof LispSourceDestLCAFAddress);
707         LispSourceDestLCAFAddress sourceDestFromNetwork = (LispSourceDestLCAFAddress) fromNetwork;
708
709         LispAddress receivedAddr1 = sourceDestFromNetwork.getSrcAddress();
710         LispAddress receivedAddr2 = sourceDestFromNetwork.getDstAddress();
711
712         assertTrue(receivedAddr1 instanceof LispIpv4Address);
713         assertTrue(receivedAddr2 instanceof LispMACAddress);
714
715         LispIpv4Address receivedIP = (LispIpv4Address) receivedAddr1;
716         LispMACAddress receivedMAC = (LispMACAddress) receivedAddr2;
717
718         assertEquals(ipString, receivedIP.getAddress().getHostAddress());
719         assertArrayEquals(fakeMAC, receivedMAC.getMAC());
720     }
721
722     @Test
723     public void registerAndQuery__ListLCAF() throws SocketTimeoutException {
724         byte[] macAddress = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5, (byte) 6 };
725         String ipAddress = "10.20.255.30";
726         List<LispAddress> list = new ArrayList<LispAddress>();
727         list.add(new LispMACAddress(macAddress));
728         list.add(new LispIpv4Address(ipAddress));
729
730         LispListLCAFAddress listAddrToSend = new LispListLCAFAddress((byte) 0, list);
731
732         MapReply reply = registerAddressAndQuery(listAddrToSend);
733
734         LispAddress receivedAddress = reply.getEidToLocatorRecords().get(0).getPrefix();
735
736         assertTrue(receivedAddress instanceof LispListLCAFAddress);
737
738         LispListLCAFAddress listAddrFromNetwork = (LispListLCAFAddress) receivedAddress;
739         LispAddress receivedAddr1 = listAddrFromNetwork.getAddresses().get(0);
740         LispAddress receivedAddr2 = listAddrFromNetwork.getAddresses().get(1);
741
742         assertTrue(receivedAddr1 instanceof LispMACAddress);
743         assertTrue(receivedAddr2 instanceof LispIpv4Address);
744
745         assertArrayEquals(macAddress, ((LispMACAddress) receivedAddr1).getMAC());
746         assertEquals(ipAddress, ((LispIpv4Address) receivedAddr2).getAddress().getHostAddress());
747     }
748
749     @Test
750     public void registerAndQuerySegmentLCAF() throws SocketTimeoutException {
751         String ipAddress = "10.20.255.30";
752         int instanceId = 6;
753         LispIpv4Address lispIpAddress = new LispIpv4Address(ipAddress);
754         LispSegmentLCAFAddress addressToSend = new LispSegmentLCAFAddress((byte) 0, instanceId, lispIpAddress);
755
756         MapReply reply = registerAddressAndQuery(addressToSend);
757
758         LispAddress receivedAddress = reply.getEidToLocatorRecords().get(0).getPrefix();
759         assertTrue(receivedAddress instanceof LispSegmentLCAFAddress);
760
761         LispSegmentLCAFAddress segmentfromNetwork = (LispSegmentLCAFAddress) receivedAddress;
762         LispAddress addrFromSegment = segmentfromNetwork.getAddress();
763         assertTrue(addrFromSegment instanceof LispIpv4Address);
764         assertEquals(ipAddress, ((LispIpv4Address) addrFromSegment).getAddress().getHostAddress());
765
766         assertEquals(instanceId, segmentfromNetwork.getInstanceId());
767     }
768
769     @Test
770     public void registerAndQuery__TrafficEngineering() throws SocketTimeoutException {
771         byte[] macAddress = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5, (byte) 6 };
772         String ipAddress = "10.20.255.30";
773         List<ReencapHop> hops = new ArrayList<ReencapHop>();
774         boolean f = false;
775         boolean t = true;
776         hops.add(new ReencapHop(new LispMACAddress(macAddress), (short) 0, t, t, t));
777         hops.add(new ReencapHop(new LispIpv4Address(ipAddress), (short) 0, f, f, f));
778
779         LispTrafficEngineeringLCAFAddress addressToSend = new LispTrafficEngineeringLCAFAddress((byte) 0, hops);
780
781         MapReply reply = registerAddressAndQuery(addressToSend);
782
783         assertTrue(reply.getEidToLocatorRecords().get(0).getPrefix() instanceof LispTrafficEngineeringLCAFAddress);
784
785         LispTrafficEngineeringLCAFAddress receivedAddress = (LispTrafficEngineeringLCAFAddress) reply.getEidToLocatorRecords().get(0).getPrefix();
786
787         ReencapHop hop1 = receivedAddress.getHops().get(0);
788         ReencapHop hop2 = receivedAddress.getHops().get(1);
789
790         assertEquals(t, hop1.isLookup());
791         assertEquals(t, hop1.isRLOCProbe());
792         assertEquals(t, hop1.isStrict());
793
794         assertEquals(f, hop2.isLookup());
795         assertEquals(f, hop2.isRLOCProbe());
796         assertEquals(f, hop2.isStrict());
797
798         assertTrue(hop1.getHop() instanceof LispMACAddress);
799         assertTrue(hop2.getHop() instanceof LispIpv4Address);
800
801         LispMACAddress receivedMACAddress = (LispMACAddress) hop1.getHop();
802         LispIpv4Address receivedIPAddress = (LispIpv4Address) hop2.getHop();
803
804         assertArrayEquals(macAddress, receivedMACAddress.getMAC());
805         assertEquals(ipAddress, receivedIPAddress.getAddress().getHostAddress());
806     }
807
808     @Test
809     public void registerAndQuery__ApplicationData() throws SocketTimeoutException {
810         String ipAddress = "1.2.3.4";
811         byte protocol = (byte) 1;
812         int ipTOs = 2;
813         short localPort = (short) 3;
814         short remotePort = (short) 4;
815
816         LispApplicationDataLCAFAddress addressToSend = new LispApplicationDataLCAFAddress((byte) 0, protocol, ipTOs, localPort, remotePort,
817                 new LispIpv4Address(ipAddress));
818
819         MapReply reply = registerAddressAndQuery(addressToSend);
820
821         LispAddress receivedAddress = reply.getEidToLocatorRecords().get(0).getPrefix();
822
823         assertTrue(receivedAddress instanceof LispApplicationDataLCAFAddress);
824
825         LispApplicationDataLCAFAddress receivedApplicationDataAddress = (LispApplicationDataLCAFAddress) receivedAddress;
826         assertEquals(protocol, receivedApplicationDataAddress.getProtocol());
827         assertEquals(ipTOs, receivedApplicationDataAddress.getIPTos());
828         assertEquals(localPort, receivedApplicationDataAddress.getLocalPort());
829         assertEquals(remotePort, receivedApplicationDataAddress.getRemotePort());
830
831         LispIpv4Address ipAddressReceived = (LispIpv4Address) receivedApplicationDataAddress.getAddress();
832         assertEquals(ipAddress, ipAddressReceived.getAddress().getHostAddress());
833     }
834
835     @Test
836     public void eidPrefixLookupIPv4() throws SocketTimeoutException {
837         runPrefixTest(new LispIpv4Address("1.2.3.4"), 16, new LispIpv4Address("1.2.3.2"), new LispIpv4Address("1.1.1.1"), (byte) 32);
838     }
839
840     @Test
841     public void eidPrefixLookupIPv6() throws SocketTimeoutException {
842         runPrefixTest(new LispIpv6Address("1:2:3:4:5:6:7:8"), 64, new LispIpv6Address("1:2:3:4:5:1:2:3"), new LispIpv6Address("1:2:3:1:2:3:1:2"),
843                 (byte) 128);
844     }
845
846     private void runPrefixTest(LispAddress registerEID, int registerdMask, LispAddress matchedAddress, LispAddress unMatchedAddress, byte mask)
847             throws SocketTimeoutException {
848         MapRegister mapRegister = new MapRegister();
849         mapRegister.setWantMapNotify(true);
850         mapRegister.setNonce(8);
851         EidToLocatorRecord etlr = new EidToLocatorRecord();
852         etlr.setPrefix(registerEID);
853         etlr.setMaskLength(registerdMask);
854         etlr.setRecordTtl(254);
855         LocatorRecord record = new LocatorRecord();
856         record.setLocator(new LispIpv4Address("4.3.2.1"));
857         etlr.addLocator(record);
858         mapRegister.addEidToLocator(etlr);
859         sendMapRegister(mapRegister);
860         MapNotify mapNotify = recieveMapNotify();
861         assertEquals(8, mapNotify.getNonce());
862         MapRequest mapRequest = new MapRequest();
863         mapRequest.setNonce(4);
864         mapRequest.addEidRecord(new EidRecord(mask, matchedAddress));
865         mapRequest.addItrRloc(new LispIpv4Address(ourAddress));
866         sendMapRequest(mapRequest);
867         MapReply mapReply = recieveMapReply();
868         assertEquals(4, mapReply.getNonce());
869         assertEquals(record.getLocator(), mapReply.getEidToLocatorRecords().get(0).getLocators().get(0).getLocator());
870         mapRequest.getEids().get(0).setPrefix(unMatchedAddress);
871         sendMapRequest(mapRequest);
872         mapReply = recieveMapReply();
873         assertEquals(0, mapReply.getEidToLocatorRecords().get(0).getLocators().size());
874     }
875
876     public void mapRequestMapRegisterAndMapRequest() throws SocketTimeoutException {
877
878         LispIpv4Address eid = new LispIpv4Address("1.2.3.4");
879         MapRequest mapRequest = new MapRequest();
880         mapRequest.setNonce(4);
881         mapRequest.addEidRecord(new EidRecord((byte) 32, eid));
882         mapRequest.addItrRloc(new LispIpv4Address(ourAddress));
883         sendMapRequest(mapRequest);
884         MapReply mapReply = recieveMapReply();
885         assertEquals(4, mapReply.getNonce());
886         assertEquals(0, mapReply.getEidToLocatorRecords().get(0).getLocators().size());
887         MapRegister mapRegister = new MapRegister();
888         mapRegister.setWantMapNotify(true);
889         mapRegister.setNonce(8);
890         EidToLocatorRecord etlr = new EidToLocatorRecord();
891         etlr.setPrefix(eid);
892         etlr.setMaskLength(32);
893         etlr.setRecordTtl(254);
894         LocatorRecord record = new LocatorRecord();
895         record.setLocator(new LispIpv4Address("4.3.2.1"));
896         etlr.addLocator(record);
897         mapRegister.addEidToLocator(etlr);
898         sendMapRegister(mapRegister);
899         MapNotify mapNotify = recieveMapNotify();
900         assertEquals(8, mapNotify.getNonce());
901         sendMapRequest(mapRequest);
902         mapReply = recieveMapReply();
903         assertEquals(4, mapReply.getNonce());
904         assertEquals(record.getLocator(), mapReply.getEidToLocatorRecords().get(0).getLocators().get(0).getLocator());
905
906     }
907
908     private MapReply recieveMapReply() throws SocketTimeoutException {
909         return MapReplySerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket().getData()));
910     }
911
912     private MapNotify recieveMapNotify() throws SocketTimeoutException {
913         return MapNotifySerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket().getData()));
914     }
915
916     private void sendMapRequest(MapRequest mapRequest) {
917         sendPacket(MapRequestSerializer.getInstance().serialize(mapRequest).array());
918     }
919
920     private void sendMapRegister(MapRegister mapRegister) {
921         sendPacket(MapRegisterSerializer.getInstance().serialize(mapRegister).array());
922     }
923
924     @Test
925     public void mapRegisterWithAuthenticationWithoutConfiguringAKey() throws SocketTimeoutException {
926         sendPacket(mapRegisterPacketWithAuthenticationAndMapNotify);
927         try {
928             receivePacket(3000);
929             // If didn't timeout then fail:
930             fail();
931         } catch (SocketTimeoutException ste) {
932         }
933     }
934
935     @Test
936     public void mapRegisterWithMapNotifyWithListLcaf() throws SocketTimeoutException {
937         sendPacket(mapRegisterPacketWithNotifyWithListLCAFAndDistinguishedName);
938         ByteBuffer readBuf = ByteBuffer.wrap(receivePacket().getData());
939         MapNotify reply = MapNotifySerializer.getInstance().deserialize(readBuf);
940         EidToLocatorRecord etlr = reply.getEidToLocatorRecords().get(0);
941         List<LocatorRecord> locators = etlr.getLocators();
942         assertEquals(true, (locators.get(0).getLocator() instanceof LispListLCAFAddress));
943         LispListLCAFAddress listLCAF = (LispListLCAFAddress) locators.get(0).getLocator();
944         LispListLCAFAddress innerList = (LispListLCAFAddress) listLCAF.getAddresses().get(1);
945         LispDistinguishedNameAddress dn = new LispDistinguishedNameAddress("david");
946         assertEquals(dn, ((LispDistinguishedNameAddress) innerList.getAddresses().get(0)));
947         assertEquals(7, reply.getNonce());
948     }
949
950     @Test
951     public void mapRegisterWithoutMapNotify() {
952         sendPacket(mapRegisterPacketWithoutNotify);
953         try {
954             receivePacket(3000);
955             // If didn't timeout then fail:
956             fail();
957         } catch (SocketTimeoutException ste) {
958         }
959     }
960
961     private void sendPacket(byte[] bytesToSend) {
962         try {
963             DatagramPacket packet = new DatagramPacket(bytesToSend, bytesToSend.length);
964             initPacketAddress(packet);
965             logger.info("Sending MapRegister to LispPlugin on socket");
966             socket.send(packet);
967         } catch (Throwable t) {
968             t.printStackTrace();
969             fail();
970         }
971     }
972
973     private DatagramPacket receivePacket() throws SocketTimeoutException {
974         return receivePacket(6000);
975     }
976
977     private DatagramPacket receivePacket(int timeout) throws SocketTimeoutException {
978         try {
979             byte[] buffer = new byte[4096];
980             DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
981             logger.info("Waiting for packet from socket...");
982             socket.setSoTimeout(timeout);
983             socket.receive(receivePacket);
984             logger.info("Recieved packet from socket!");
985             return receivePacket;
986         } catch (SocketTimeoutException ste) {
987             throw ste;
988         } catch (Throwable t) {
989             t.printStackTrace();
990             fail();
991             return null;
992         }
993     }
994
995     private void initPacketAddress(DatagramPacket packet) throws UnknownHostException {
996         packet.setAddress(InetAddress.getByName(lispBindAddress));
997         packet.setPort(lispPortNumber);
998     }
999
1000     private DatagramSocket initSocket(DatagramSocket socket) {
1001         try {
1002             socket = new DatagramSocket(new InetSocketAddress(ourAddress, LispMessage.PORT_NUM));
1003         } catch (SocketException e) {
1004             e.printStackTrace();
1005             fail();
1006         }
1007         return socket;
1008     }
1009
1010     private byte[] extractWSUdpByteArray(String wiresharkHex) {
1011         final int HEADER_LEN = 42;
1012         byte[] res = new byte[1000];
1013         String[] split = wiresharkHex.split(" ");
1014         int counter = 0;
1015         for (String cur : split) {
1016             cur = cur.trim();
1017             if (cur.length() == 2) {
1018                 ++counter;
1019                 if (counter > HEADER_LEN) {
1020                     res[counter - HEADER_LEN - 1] = (byte) Integer.parseInt(cur, 16);
1021                 }
1022
1023             }
1024         }
1025         return Arrays.copyOf(res, counter - HEADER_LEN);
1026     }
1027
1028     private String stateToString(int state) {
1029         switch (state) {
1030         case Bundle.ACTIVE:
1031             return "ACTIVE";
1032         case Bundle.INSTALLED:
1033             return "INSTALLED";
1034         case Bundle.RESOLVED:
1035             return "RESOLVED";
1036         case Bundle.UNINSTALLED:
1037             return "UNINSTALLED";
1038         default:
1039             return "Not CONVERTED";
1040         }
1041     }
1042
1043     @Before
1044     public void areWeReady() throws InvalidSyntaxException {
1045         assertNotNull(bc);
1046         boolean debugit = false;
1047         Bundle b[] = bc.getBundles();
1048         for (Bundle element : b) {
1049             int state = element.getState();
1050             if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
1051                 System.out.println("Bundle:" + element.getSymbolicName() + " state:" + stateToString(state));
1052
1053                 // UNCOMMENT to see why bundles didn't resolve!
1054
1055                 //                try {
1056                 //                    String host = element.getHeaders().get(Constants.FRAGMENT_HOST);
1057                 //                    if (host != null) {
1058                 //                        logger.warn("Bundle " + element.getSymbolicName() + " is a fragment which is part of: " + host);
1059                 //                        logger.warn("Required imports are: " + element.getHeaders().get(Constants.IMPORT_PACKAGE));
1060                 //                    } else {
1061                 //                        //  if (element.getSymbolicName().equals("org.opendaylight.controller.sal-core-api")) {
1062                 //                        element.start();
1063                 //                        // }
1064                 //                    }
1065                 //                } catch (BundleException e) {
1066                 //                    logger.error("BundleException:", e);
1067                 //                    fail();
1068                 //                }
1069                 //
1070                 //                debugit = true;
1071
1072             }
1073         }
1074         if (debugit) {
1075             logger.warn(("Do some debugging because some bundle is unresolved"));
1076         }
1077         ServiceReference r = bc.getServiceReference(IFlowMapping.class.getName());
1078         if (r != null) {
1079             this.lms = (IFlowMapping) bc.getService(r);
1080         }
1081         // If LispMappingServer is null, cannot work
1082         assertNotNull(this.lms);
1083
1084         // Uncomment this code to Know which services were actually loaded to
1085         // BundleContext
1086         /*
1087          * for (ServiceReference sr : bc.getAllServiceReferences(null, null)) {
1088          * logger.info(sr.getBundle().getSymbolicName());
1089          * logger.info(sr.toString()); }
1090          */
1091     }
1092 }