blob: ed784769e52c753460617da171dedf19b9d9348c [file] [log] [blame]
Andrew Brown3f2521a2015-01-17 22:10:15 -08001/*
2 * File name: ClientObserver.java
3 *
4 * Purpose:
5 *
6 * © Copyright Intel Corporation. All rights reserved.
7 * Intel Corporation, 2200 Mission College Boulevard,
8 * Santa Clara, CA 95052-8119, USA
9 */
10package com.intel.jndn.utils;
11
12import java.util.ArrayList;
13import java.util.List;
14import java.util.Observable;
15import java.util.Observer;
16import net.named_data.jndn.Data;
17import net.named_data.jndn.Interest;
18import net.named_data.jndn.OnData;
19
20/**
21 *
22 * @author Andrew Brown <andrew.brown@intel.com>
23 */
24public class ClientObserver implements Observer {
25
26 protected List<ClientObservableEvent> events = new ArrayList<>();
27 protected long timestamp;
28 protected OnData then;
29 protected boolean stopThread;
30
31 public ClientObserver(){
32 timestamp = System.currentTimeMillis();
33 }
34
35 @Override
36 public void update(Observable o, Object arg) {
37 ClientObservableEvent event = (ClientObservableEvent) arg;
38 events.add(event);
39 if(Data.class.isInstance(event.packet)){
40 then.onData(null, (Data) event.packet);
41 }
42 }
43
44 public ClientObserver then(OnData handler){
45 then = handler;
46 return this;
47 }
48
49 public int count(Class type) {
50 int count = 0;
51 for (ClientObservableEvent event : events) {
52 if (type.isInstance(event.packet)) {
53 count++;
54 }
55 }
56 return count;
57 }
58
59 public int requests() {
60 return count(Interest.class);
61 }
62
63 public int responses() {
64 return count(Data.class);
65 }
66
67 public int errors(){
68 return count(Exception.class);
69 }
70
71 /**
72 * Get time since observer start
73 * @return
74 */
75 public long getTimeSinceStart(){
76 if(getLast() != null){
77 return getLast().getTimestamp() - timestamp;
78 }
79 return -1;
80 }
81
82 public ClientObservableEvent getFirst() {
83 if (events.size() > 0) {
84 return events.get(0);
85 }
86 return null;
87 }
88
89 public ClientObservableEvent getLast() {
90 if (events.size() > 0) {
91 return events.get(events.size() - 1);
92 }
93 return null;
94 }
95
96 public void stop(){
97 stopThread = true;
98 }
99
100 public boolean mustStop(){
101 return stopThread;
102 }
103}