blob: 269fe5c3017b856d7bf5c0522b846ac0876b73ba [file] [log] [blame]
Andrew Brown3f2521a2015-01-17 22:10:15 -08001/*
2 * File name: Client.java
3 *
4 * Purpose: Provide a client to simplify information retrieval over the NDN
5 * network.
6 *
7 * © Copyright Intel Corporation. All rights reserved.
8 * Intel Corporation, 2200 Mission College Boulevard,
9 * Santa Clara, CA 95052-8119, USA
10 */
11package com.intel.jndn.utils;
12
13import java.io.IOException;
14import net.named_data.jndn.Data;
15import net.named_data.jndn.Face;
16import net.named_data.jndn.ForwardingFlags;
17import net.named_data.jndn.Interest;
18import net.named_data.jndn.Name;
19import net.named_data.jndn.OnData;
20import net.named_data.jndn.OnInterest;
21import net.named_data.jndn.OnRegisterFailed;
22import net.named_data.jndn.OnTimeout;
23import net.named_data.jndn.encoding.EncodingException;
24import net.named_data.jndn.transport.Transport;
25import org.apache.logging.log4j.LogManager;
26import org.apache.logging.log4j.Logger;
27
28/**
29 *
30 * @author Andrew Brown <andrew.brown@intel.com>
31 */
32public class Client {
33
Andrew Brown7b1daf32015-01-19 16:36:01 -080034 public static final long DEFAULT_SLEEP_TIME = 20;
35 public static final long DEFAULT_TIMEOUT = 2000;
36 private static final Logger logger = LogManager.getLogger();
Andrew Brown3f2521a2015-01-17 22:10:15 -080037
Andrew Brown7b1daf32015-01-19 16:36:01 -080038 /**
39 * Synchronously retrieve the Data for an Interest; this will block until
40 * complete (i.e. either data is received or the interest times out).
41 *
42 * @param face
43 * @param interest
44 * @return Data packet or null
45 */
46 public Data getSync(Face face, Interest interest) {
47 // setup event
48 long startTime = System.currentTimeMillis();
49 final ClientObservableEvent event = new ClientObservableEvent(); // this event is used without observer/observables for speed; just serves as a final reference into the callbacks
Andrew Brown3f2521a2015-01-17 22:10:15 -080050
Andrew Brown7b1daf32015-01-19 16:36:01 -080051 // send interest
52 try {
53 face.expressInterest(interest, new OnData() {
54 @Override
55 public void onData(Interest interest, Data data) {
56 event.setTimestamp(System.currentTimeMillis());
57 event.setSuccess(true);
58 event.setPacket(data);
59 }
60 }, new OnTimeout() {
61 @Override
62 public void onTimeout(Interest interest) {
63 event.setTimestamp(System.currentTimeMillis());
64 event.setSuccess(false);
65 event.setPacket(new Object());
66 }
67 });
68 } catch (IOException e) {
69 logger.warn("IO failure while sending interest.", e);
70 return null;
71 }
Andrew Brown3f2521a2015-01-17 22:10:15 -080072
Andrew Brown7b1daf32015-01-19 16:36:01 -080073 // process events until a response is received or timeout
74 while (event.getPacket() == null) {
75 try {
76 synchronized (face) {
77 face.processEvents();
78 }
79 } catch (IOException | EncodingException e) {
80 logger.warn("Failed to process events.", e);
81 return null;
82 }
83 sleep();
84 }
Andrew Brown3f2521a2015-01-17 22:10:15 -080085
Andrew Brown7b1daf32015-01-19 16:36:01 -080086 // return
87 logger.debug("Request time (ms): " + (event.getTimestamp() - startTime));
88 return (event.isSuccess()) ? (Data) event.getPacket() : null;
89 }
Andrew Brown3f2521a2015-01-17 22:10:15 -080090
Andrew Brown7b1daf32015-01-19 16:36:01 -080091 /**
92 * Synchronously retrieve the Data for a Name using a default interest (e.g. 2
93 * second timeout); this will block until complete (i.e. either data is
94 * received or the interest times out).
95 *
96 * @param face
97 * @param name
98 * @return
99 */
100 public Data getSync(Face face, Name name) {
101 return getSync(face, getDefaultInterest(name));
102 }
Andrew Brown3f2521a2015-01-17 22:10:15 -0800103
Andrew Brown7b1daf32015-01-19 16:36:01 -0800104 /**
105 * Asynchronously retrieve the Data for a given interest; use the returned
106 * ClientObserver to handle the Data when it arrives. E.g.: Client.get(face,
107 * interest).then((data) -> doSomething(data));
108 *
109 * @param face
110 * @param interest
111 * @return
112 */
113 public ClientObserver get(final Face face, final Interest interest) {
114 // setup observer
115 final ClientObserver observer = new ClientObserver();
116 final ClientObservable eventHandler = new ClientObservable();
117 eventHandler.addObserver(observer);
Andrew Brown3f2521a2015-01-17 22:10:15 -0800118
Andrew Brown7b1daf32015-01-19 16:36:01 -0800119 // setup background thread
120 Thread backgroundThread = new Thread(new Runnable() {
121 @Override
122 public void run() {
123 // send interest
124 try {
125 face.expressInterest(interest, eventHandler, eventHandler);
126 } catch (IOException e) {
127 logger.warn("IO failure while sending interest.", e);
128 eventHandler.notify(e);
129 }
Andrew Brown3f2521a2015-01-17 22:10:15 -0800130
Andrew Brown7b1daf32015-01-19 16:36:01 -0800131 // process events until a response is received or timeout
132 while (observer.responses() == 0 && observer.errors() == 0 && !observer.mustStop()) {
133 try {
134 synchronized (face) {
135 face.processEvents();
136 }
137 } catch (IOException | EncodingException e) {
138 logger.warn("Failed to process events.", e);
139 eventHandler.notify(e);
140 }
141 sleep();
142 }
143
144 // finished
145 logger.trace("Received response; stopping thread.");
146 }
147 });
148 backgroundThread.setName(String.format("Client.get(%s)", interest.getName().toUri()));
149 backgroundThread.setDaemon(true);
150 backgroundThread.start();
Andrew Brown3f2521a2015-01-17 22:10:15 -0800151
Andrew Brown7b1daf32015-01-19 16:36:01 -0800152 // return
153 return observer;
154 }
Andrew Brown3f2521a2015-01-17 22:10:15 -0800155
Andrew Brown7b1daf32015-01-19 16:36:01 -0800156 /**
157 * Asynchronously retrieve the Data for a Name using default Interest
158 * parameters; see get(Face, Interest) for examples.
159 *
160 * @param face
161 * @param name
162 * @return
163 */
164 public ClientObserver get(Face face, Name name) {
165 return get(face, getDefaultInterest(name));
166 }
Andrew Brown3f2521a2015-01-17 22:10:15 -0800167
Andrew Brown7b1daf32015-01-19 16:36:01 -0800168 /**
169 * Synchronously serve a Data on the given face until one request accesses the
170 * data; will return incoming Interest request. E.g.: Interest request =
171 * Client.putSync(face, data);
172 *
173 * @param face
174 * @param data
175 * @return
176 */
177 public Interest putSync(Face face, final Data data) {
178 // setup event
179 long startTime = System.currentTimeMillis();
180 final String dataName = data.getName().toUri();
181 final ClientObservableEvent event = new ClientObservableEvent();
Andrew Brown3f2521a2015-01-17 22:10:15 -0800182
Andrew Brown7b1daf32015-01-19 16:36:01 -0800183 // setup flags
184 ForwardingFlags flags = new ForwardingFlags();
185 flags.setCapture(true);
Andrew Brown3f2521a2015-01-17 22:10:15 -0800186
Andrew Brown7b1daf32015-01-19 16:36:01 -0800187 // register the data name on the face
188 try {
189 face.registerPrefix(data.getName(), new OnInterest() {
190 @Override
191 public void onInterest(Name prefix, Interest interest, Transport transport, long registeredPrefixId) {
192 try {
193 transport.send(data.wireEncode().buf());
194 logger.debug("Sent data: " + dataName);
195 event.fromPacket(interest);
196 } catch (IOException e) {
197 logger.error("Failed to send data for: " + dataName);
198 event.fromPacket(e);
199 }
200 }
201 }, new OnRegisterFailed() {
202 @Override
203 public void onRegisterFailed(Name prefix) {
204 event.fromPacket(new Exception("Failed to register name: " + dataName));
205 }
206 }, flags);
207 logger.info("Registered data: " + dataName);
208 } catch (IOException e) {
209 logger.error("Could not connect to face to register prefix: " + dataName, e);
210 event.fromPacket(e);
211 } catch (net.named_data.jndn.security.SecurityException e) {
212 logger.error("Error registering prefix: " + dataName, e);
213 event.fromPacket(e);
214 }
Andrew Brown3f2521a2015-01-17 22:10:15 -0800215
Andrew Brown7b1daf32015-01-19 16:36:01 -0800216 // process events until one response is sent or error
217 while (event.getPacket() == null) {
218 try {
219 synchronized (face) {
220 face.processEvents();
221 }
222 } catch (IOException | EncodingException e) {
223 logger.warn("Failed to process events.", e);
224 event.fromPacket(e);
225 }
226 sleep();
227 }
Andrew Brown3f2521a2015-01-17 22:10:15 -0800228
Andrew Brown7b1daf32015-01-19 16:36:01 -0800229 // return
230 logger.debug("Request time (ms): " + (event.getTimestamp() - startTime));
231 return (event.isSuccess()) ? (Interest) event.getPacket() : null;
232 }
Andrew Brown3f2521a2015-01-17 22:10:15 -0800233
Andrew Brown7b1daf32015-01-19 16:36:01 -0800234 /**
235 * Asynchronously serve a Data on the given face until an observer stops it.
236 * E.g.: ClientObserver observer = Client.put(face, data); // when finished
237 * serving the data, stop the background thread observer.stop();
238 *
239 * @param face
240 * @param data
241 * @return
242 */
243 public ClientObserver put(final Face face, final Data data) {
244 // setup observer
245 final ClientObserver observer = new ClientObserver();
246 final ClientObservable eventHandler = new ClientObservable();
247 eventHandler.addObserver(observer);
Andrew Brown3f2521a2015-01-17 22:10:15 -0800248
Andrew Brown7b1daf32015-01-19 16:36:01 -0800249 // setup handlers
250 final OnInterest interestHandler = new OnInterest() {
251 @Override
252 public void onInterest(Name prefix, Interest interest, Transport transport, long registeredPrefixId) {
253 try {
254 transport.send(data.wireEncode().buf());
255 } catch (IOException e) {
256 logger.error("Failed to send data for: " + data.getName().toUri());
257 eventHandler.onError(e);
258 }
259 }
260 };
261 final OnRegisterFailed failureHandler = new OnRegisterFailed() {
262 @Override
263 public void onRegisterFailed(Name prefix) {
264 logger.error("Failed to register name to put: " + data.getName().toUri());
265 eventHandler.onError(new Exception("Failed to register name to put: " + data.getName().toUri()));
266 }
267 };
268 final ForwardingFlags flags = new ForwardingFlags();
269 flags.setCapture(true);
Andrew Brown3f2521a2015-01-17 22:10:15 -0800270
Andrew Brown7b1daf32015-01-19 16:36:01 -0800271 // setup background thread
272 Thread backgroundThread = new Thread(new Runnable() {
273 @Override
274 public void run() {
275 // register name on the face
276 try {
277 face.registerPrefix(data.getName(), interestHandler, failureHandler, flags);
278 logger.info("Registered data : " + data.getName().toUri());
279 } catch (IOException e) {
280 logger.error("Could not connect to face to register prefix: " + data.getName().toUri(), e);
281 eventHandler.onError(e);
282 } catch (net.named_data.jndn.security.SecurityException e) {
283 logger.error("Error registering prefix: " + data.getName().toUri(), e);
284 eventHandler.onError(e);
285 }
Andrew Brown3f2521a2015-01-17 22:10:15 -0800286
Andrew Brown7b1daf32015-01-19 16:36:01 -0800287 // process events until a request is received
288 while (observer.requests() == 0 && observer.errors() == 0 && !observer.mustStop()) {
289 try {
290 synchronized (face) {
291 face.processEvents();
292 }
293 } catch (IOException | EncodingException e) {
294 logger.warn("Failed to process events.", e);
295 observer.update(eventHandler, new ClientObservableEvent());
296 }
297 sleep();
298 }
299 }
300 });
301 backgroundThread.setName(String.format("Client.put(%s)", data.getName().toUri()));
302 backgroundThread.setDaemon(true);
303 backgroundThread.start();
Andrew Brown3f2521a2015-01-17 22:10:15 -0800304
Andrew Brown7b1daf32015-01-19 16:36:01 -0800305 return observer;
306 }
Andrew Brown3f2521a2015-01-17 22:10:15 -0800307
Andrew Brown7b1daf32015-01-19 16:36:01 -0800308 /**
309 * Put the current thread to sleep to allow time for IO
310 */
311 protected void sleep() {
312 try {
313 Thread.currentThread().sleep(DEFAULT_SLEEP_TIME);
314 } catch (InterruptedException e) {
315 logger.error("Event loop interrupted.", e);
316 }
317 }
318
319 /**
320 * Create a default interest for a given Name using some common settings: -
321 * lifetime: 2 seconds
322 *
323 * @param name
324 * @return
325 */
326 public Interest getDefaultInterest(Name name) {
327 Interest interest = new Interest(name, DEFAULT_TIMEOUT);
328 return interest;
329 }
Andrew Brown3f2521a2015-01-17 22:10:15 -0800330}