blob: 34b82065d4ac5fb9323c7c6462e899490992dc25 [file] [log] [blame]
Andrew Brown3831baf2015-01-19 13:38:52 -08001/*
andrewsbrown533c6ef2015-03-03 16:08:41 -08002 * jndn-mock
3 * Copyright (c) 2015, Intel Corporation.
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms and conditions of the GNU Lesser General Public License,
7 * version 3, as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope it will be useful, but WITHOUT ANY
10 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
12 * more details.
Andrew Brown3831baf2015-01-19 13:38:52 -080013 */
14package com.intel.jndn.mock;
15
16import java.io.IOException;
andrewsbrown1f28bcf2015-04-20 13:29:20 -070017import java.nio.ByteBuffer;
Andrew Brown3831baf2015-01-19 13:38:52 -080018import java.util.HashMap;
19import java.util.Map.Entry;
Andrew Brownec1b0d02015-02-21 13:11:42 -080020import java.util.logging.Logger;
Andrew Brown3831baf2015-01-19 13:38:52 -080021import net.named_data.jndn.Data;
Andrew Brownb91e6902015-02-12 09:01:50 -080022import net.named_data.jndn.Face;
Andrew Brown3831baf2015-01-19 13:38:52 -080023import net.named_data.jndn.ForwardingFlags;
24import net.named_data.jndn.Interest;
andrewsbrown1f28bcf2015-04-20 13:29:20 -070025import net.named_data.jndn.InterestFilter;
Andrew Brown3831baf2015-01-19 13:38:52 -080026import net.named_data.jndn.Name;
27import net.named_data.jndn.Node;
28import net.named_data.jndn.OnData;
29import net.named_data.jndn.OnInterest;
andrewsbrown1f28bcf2015-04-20 13:29:20 -070030import net.named_data.jndn.OnInterestCallback;
Andrew Brown3831baf2015-01-19 13:38:52 -080031import net.named_data.jndn.OnRegisterFailed;
32import net.named_data.jndn.OnTimeout;
33import net.named_data.jndn.encoding.EncodingException;
34import net.named_data.jndn.encoding.WireFormat;
andrewsbrown1f28bcf2015-04-20 13:29:20 -070035import net.named_data.jndn.security.SecurityException;
andrewsbrownebb72a82015-03-31 13:31:18 -070036import net.named_data.jndn.transport.Transport;
Andrew Brown3831baf2015-01-19 13:38:52 -080037
38/**
Andrew Brownb91e6902015-02-12 09:01:50 -080039 * <p>
40 * Use the MockTransport to mock sending data over the network. Allows for
41 * testing NDN applications while simulating network IO. TODO implement longest
42 * prefix match here for comprehensive testing.
43 * </p>
44 * <p>
45 * Usage
46 * </p>
47 * <pre><code>
48 * Face mockFace = new MockFace();
49 * mockFace.registerPrefix(...); // as usual
50 * mockFace.expressInterest(...); // as usual
51 *
52 * // also, simply inject a response that will be returned for an expressed interest
53 * mockFace.addResponse(interestName, data);
54 * </pre></code>
Andrew Brown3831baf2015-01-19 13:38:52 -080055 *
56 * @author Andrew Brown <andrew.brown@intel.com>
57 */
andrewsbrown1f28bcf2015-04-20 13:29:20 -070058public class MockFace extends FaceExtension {
Andrew Brown3831baf2015-01-19 13:38:52 -080059
Andrew Brownec1b0d02015-02-21 13:11:42 -080060 private static final Logger logger = Logger.getLogger(MockFace.class.getName());
Andrew Brown3831baf2015-01-19 13:38:52 -080061 private final Node node_;
62 HashMap<String, Data> responseMap = new HashMap<>();
63 HashMap<Long, MockOnInterestHandler> handlerMap = new HashMap<>();
64 long lastRegisteredId = 0;
65
66 /**
67 * Create a new Face to mock communication over the network; all packets are
68 * maintained in memory
69 */
70 public MockFace() {
71 node_ = new Node(new MockTransport(), null);
72 }
73
74 /**
andrewsbrownebb72a82015-03-31 13:31:18 -070075 * @return a reference to the current MockTransport
76 */
77 public MockTransport getTransport() {
78 return (MockTransport) node_.getTransport();
79 }
80
81 /**
Andrew Brown3831baf2015-01-19 13:38:52 -080082 * Add a response Data packet to send immediately when an Interest with a
83 * matching name is received; will continue to respond with the same packet
84 * over multiple requests. This will preempt any registered OnInterest
85 * handlers.
86 *
87 * @param name
88 * @param data
89 */
90 public void addResponse(Name name, Data data) {
Andrew Brownec1b0d02015-02-21 13:11:42 -080091 logger.fine("Added response for: " + name.toUri());
Andrew Brown3831baf2015-01-19 13:38:52 -080092 responseMap.put(name.toUri(), data);
93 }
94
95 /**
96 * Stop sending a response for the given name.
97 *
98 * @param name
99 */
100 public void removeResponse(Name name) {
Andrew Brownec1b0d02015-02-21 13:11:42 -0800101 logger.fine("Removed response for: " + name.toUri());
Andrew Brown3831baf2015-01-19 13:38:52 -0800102 responseMap.remove(name);
103 }
104
105 /**
106 * Handle incoming Interest packets; when an Interest is expressed through
107 * expressInterest(), this will run to determine if: 1) any responses have
Andrew Brown8d8535b2015-01-19 15:22:06 -0800108 * been registered or 2) if any OnInterest handlers have been registered. If
109 * one of these two succeeds, this method then re-directs the Interest from
Andrew Brown3831baf2015-01-19 13:38:52 -0800110 * traveling down the network stack and returns data.
Andrew Brown8d8535b2015-01-19 15:22:06 -0800111 *
Andrew Brown3831baf2015-01-19 13:38:52 -0800112 * @param interest
113 */
114 protected void handleIncomingRequests(Interest interest) {
115 String interestName = interest.getName().toUri();
116 long registeredPrefixId = findRegisteredHandler(interest);
117 // check if response registered
118 if (responseMap.containsKey(interestName)) {
Andrew Brownec1b0d02015-02-21 13:11:42 -0800119 logger.fine("Found response for: " + interestName);
Andrew Brown3831baf2015-01-19 13:38:52 -0800120 Data data = responseMap.get(interestName);
121 ((MockTransport) node_.getTransport()).respondWith(data);
Andrew Brown8d8535b2015-01-19 15:22:06 -0800122 } // check if handler registered
Andrew Brown3831baf2015-01-19 13:38:52 -0800123 else if (registeredPrefixId != -1) {
Andrew Brownec1b0d02015-02-21 13:11:42 -0800124 logger.fine("Found handler for: " + interestName);
Andrew Brown3831baf2015-01-19 13:38:52 -0800125 MockOnInterestHandler handler = handlerMap.get(findRegisteredHandler(interest));
andrewsbrown1f28bcf2015-04-20 13:29:20 -0700126 handler.signal(interest, registeredPrefixId);
Andrew Brown8d8535b2015-01-19 15:22:06 -0800127 } // log failure
Andrew Brown3831baf2015-01-19 13:38:52 -0800128 else {
Andrew Brownec1b0d02015-02-21 13:11:42 -0800129 logger.warning("No response found for interest (aborting): " + interestName);
Andrew Brown3831baf2015-01-19 13:38:52 -0800130 }
131 }
132
133 /**
134 * Find a handler that matches the incoming interest; currently, the only
135 * flags supported are the ChildInherit flags.
Andrew Brown8d8535b2015-01-19 15:22:06 -0800136 *
Andrew Brown3831baf2015-01-19 13:38:52 -0800137 * @param interest
Andrew Brown8d8535b2015-01-19 15:22:06 -0800138 * @return
Andrew Brown3831baf2015-01-19 13:38:52 -0800139 */
140 protected long findRegisteredHandler(Interest interest) {
141 for (Entry<Long, MockOnInterestHandler> entry : handlerMap.entrySet()) {
142 MockOnInterestHandler handler = entry.getValue();
143 if (handler.flags.getChildInherit() && handler.prefix.match(interest.getName())) {
144 return entry.getKey();
145 }
146 if (handler.prefix.equals(interest.getName())) {
147 return entry.getKey();
148 }
149 }
150 return -1;
151 }
152
153 /**
154 * Helper class for holding references to OnInterest handlers
155 */
156 class MockOnInterestHandler {
157
158 Name prefix;
159 OnInterest onInterest;
andrewsbrown1f28bcf2015-04-20 13:29:20 -0700160 OnInterestCallback onInterestCallback;
Andrew Brown3831baf2015-01-19 13:38:52 -0800161 ForwardingFlags flags;
162
163 public MockOnInterestHandler(Name prefix, OnInterest onInterest, ForwardingFlags flags) {
164 this.prefix = prefix;
165 this.onInterest = onInterest;
166 this.flags = flags;
167 }
andrewsbrown1f28bcf2015-04-20 13:29:20 -0700168
169 public MockOnInterestHandler(Name prefix, OnInterestCallback onInterestCallback, ForwardingFlags flags) {
170 this.prefix = prefix;
171 this.onInterestCallback = onInterestCallback;
172 this.flags = flags;
173 }
174
175 public void signal(Interest interest, long registeredPrefixId){
176 if(onInterest != null){
177 onInterest.onInterest(prefix, interest, node_.getTransport(), registeredPrefixId);
178 }
179 if(onInterestCallback != null){
180 onInterestCallback.onInterest(prefix, interest, MockFace.this, registeredPrefixId, null);
181 }
182 }
Andrew Brown3831baf2015-01-19 13:38:52 -0800183 }
184
185 /**
186 * Send the Interest through the transport, read the entire response and call
187 * onData(interest, data).
188 *
189 * @param interest The Interest to send. This copies the Interest.
190 * @param onData When a matching data packet is received, this calls
191 * onData.onData(interest, data) where interest is the interest given to
192 * expressInterest and data is the received Data object. NOTE: You must not
193 * change the interest object - if you need to change it then make a copy.
194 * @param onTimeout If the interest times out according to the interest
195 * lifetime, this calls onTimeout.onTimeout(interest) where interest is the
196 * interest given to expressInterest. If onTimeout is null, this does not use
197 * it.
198 * @param wireFormat A WireFormat object used to encode the message.
199 * @return The pending interest ID which can be used with
200 * removePendingInterest.
201 * @throws IOException For I/O error in sending the interest.
202 */
Andrew Brownb91e6902015-02-12 09:01:50 -0800203 @Override
Andrew Brown3831baf2015-01-19 13:38:52 -0800204 public long expressInterest(Interest interest, OnData onData, OnTimeout onTimeout,
205 WireFormat wireFormat) throws IOException {
206 long id = node_.expressInterest(interest, onData, onTimeout, wireFormat);
207 handleIncomingRequests(interest);
208 return id;
209 }
210
211 /**
Andrew Brown3831baf2015-01-19 13:38:52 -0800212 * Register prefix with the connected NDN hub and call onInterest when a
213 * matching interest is received. If you have not called
214 * setCommandSigningInfo, this assumes you are connecting to NDNx. If you have
215 * called setCommandSigningInfo, this first sends an NFD registration request,
216 * and if that times out then this sends an NDNx registration request. If you
217 * need to register a prefix with NFD, you must first call
218 * setCommandSigningInfo.
219 *
220 * @param prefix A Name for the prefix to register. This copies the Name.
221 * @param onInterest When an interest is received which matches the name
222 * prefix, this calls onInterest.onInterest(prefix, interest, transport,
223 * registeredPrefixId). NOTE: You must not change the prefix object - if you
224 * need to change it then make a copy.
225 * @param onRegisterFailed If register prefix fails for any reason, this calls
226 * onRegisterFailed.onRegisterFailed(prefix).
227 * @param flags The flags for finer control of which interests are forwarded
228 * to the application.
229 * @param wireFormat A WireFormat object used to encode the message.
230 * @return The lastRegisteredId prefix ID which can be used with
231 * removeRegisteredPrefix.
232 * @throws IOException For I/O error in sending the registration request.
233 * @throws SecurityException If signing a command interest for NFD and cannot
234 * find the private key for the certificateName.
235 */
Andrew Brownb91e6902015-02-12 09:01:50 -0800236 @Override
Andrew Brown3831baf2015-01-19 13:38:52 -0800237 public long registerPrefix(Name prefix, OnInterest onInterest, OnRegisterFailed onRegisterFailed,
238 ForwardingFlags flags, WireFormat wireFormat) throws IOException, net.named_data.jndn.security.SecurityException {
andrewsbrowna52bf7d2015-04-06 13:51:53 -0700239 // since we don't send an Interest, ensure the transport is connected
andrewsbrown1f28bcf2015-04-20 13:29:20 -0700240 if (!getTransport().getIsConnected()) {
andrewsbrowna52bf7d2015-04-06 13:51:53 -0700241 getTransport().connect(node_.getConnectionInfo(), node_);
andrewsbrown1f28bcf2015-04-20 13:29:20 -0700242 }
243
Andrew Brown3831baf2015-01-19 13:38:52 -0800244 lastRegisteredId++;
245 handlerMap.put(lastRegisteredId, new MockOnInterestHandler(prefix, onInterest, flags));
246 return lastRegisteredId;
247 }
248
Andrew Brownb91e6902015-02-12 09:01:50 -0800249 @Override
andrewsbrown1f28bcf2015-04-20 13:29:20 -0700250 public long registerPrefix(Name prefix, OnInterestCallback onInterest, OnRegisterFailed onRegisterFailed, ForwardingFlags flags, WireFormat wireFormat) throws IOException, SecurityException {
251 // since we don't send an Interest, ensure the transport is connected
252 if (!getTransport().getIsConnected()) {
253 getTransport().connect(node_.getConnectionInfo(), node_);
254 }
255
256 lastRegisteredId++;
257 handlerMap.put(lastRegisteredId, new MockOnInterestHandler(prefix, onInterest, flags));
258 return lastRegisteredId;
Andrew Brown3831baf2015-01-19 13:38:52 -0800259 }
260
261 /**
Andrew Brown3831baf2015-01-19 13:38:52 -0800262 * Process any packets to receive and call callbacks such as onData,
263 * onInterest or onTimeout. This returns immediately if there is no data to
264 * receive. This blocks while calling the callbacks. You should repeatedly
265 * call this from an event loop, with calls to sleep as needed so that the
266 * loop doesn’t use 100% of the CPU. Since processEvents modifies the pending
267 * interest table, your application should make sure that it calls
268 * processEvents in the same thread as expressInterest (which also modifies
269 * the pending interest table). This may throw an exception for reading data
270 * or in the callback for processing the data. If you call this from an main
271 * event loop, you may want to catch and log/disregard all exceptions.
272 */
Andrew Brownb91e6902015-02-12 09:01:50 -0800273 @Override
Andrew Brown3831baf2015-01-19 13:38:52 -0800274 public void processEvents() throws IOException, EncodingException {
275 // Just call Node's processEvents.
276 node_.processEvents();
277 }
278
andrewsbrown1f28bcf2015-04-20 13:29:20 -0700279 @Override
280 public void removeRegisteredPrefix(long registeredPrefixId) {
281 handlerMap.remove(registeredPrefixId);
282 }
283
284 @Override
285 public long setInterestFilter(InterestFilter filter, OnInterestCallback onInterest) {
andrewsbrown0f36eee2015-05-07 01:37:48 +0100286 return node_.setInterestFilter(filter, onInterest, this);
andrewsbrown1f28bcf2015-04-20 13:29:20 -0700287 }
288
289 @Override
290 public void unsetInterestFilter(long interestFilterId) {
andrewsbrown0f36eee2015-05-07 01:37:48 +0100291 node_.unsetInterestFilter(interestFilterId);
andrewsbrown1f28bcf2015-04-20 13:29:20 -0700292 }
293
294 @Override
295 public void putData(Data data, WireFormat wireFormat) throws IOException {
296 node_.putData(data, wireFormat);
297 }
298
299 @Override
300 public void send(ByteBuffer encoding) throws IOException {
301 node_.send(encoding);
302 }
303
304 @Override
305 public boolean isLocal() throws IOException {
306 return true;
307 }
308
309 @Override
310 public void shutdown() {
311 node_.shutdown();
312 }
313
Andrew Brown3831baf2015-01-19 13:38:52 -0800314}