1 package org.djutils.demo.rmi;
2
3 import java.rmi.AlreadyBoundException;
4 import java.rmi.RemoteException;
5 import java.util.LinkedHashSet;
6 import java.util.Scanner;
7 import java.util.Set;
8
9 import org.djutils.rmi.RMIObject;
10 import org.djutils.rmi.RMIUtils;
11
12
13
14
15
16
17
18
19
20 public class Producer extends RMIObject implements ProducerInterface
21 {
22
23 private static final long serialVersionUID = 1L;
24
25
26 private Set<ListenerInterface> listeners = new LinkedHashSet<>();
27
28
29
30
31
32
33 public Producer() throws RemoteException, AlreadyBoundException
34 {
35 super("localhost", 1099, "producer");
36 }
37
38
39 @Override
40 public void addListener(final ListenerInterface listener) throws RemoteException
41 {
42 this.listeners.add(listener);
43 }
44
45
46
47
48
49
50 protected void fire(final String payload) throws RemoteException
51 {
52 for (ListenerInterface listener : this.listeners)
53 {
54 try
55 {
56 listener.notify(payload);
57 }
58 catch (Exception e)
59 {
60 System.err.println(e.getMessage());
61 }
62 }
63 }
64
65
66
67
68 protected void commands()
69 {
70 char c = 'n';
71 Scanner s = new Scanner(System.in);
72 while (c != 'x')
73 {
74 System.out.println("\nCommands: 'x' = exit; 'l' = list listeners; 's string' = send string to listeners");
75 String str = s.nextLine();
76 c = str.charAt(0);
77
78 if (c == 's')
79 {
80 String[] cmd = str.split(" ", 2);
81 if (cmd.length != 2)
82 {
83 System.err.println("not a legal command");
84 continue;
85 }
86 try
87 {
88 fire(cmd[1]);
89 }
90 catch (Exception e)
91 {
92 System.err.println(e.getMessage());
93 }
94 continue;
95 }
96
97 if (c == 'x')
98 {
99 try
100 {
101 fire("x");
102 }
103 catch (Exception e)
104 {
105 System.err.println(e.getMessage());
106 }
107 continue;
108 }
109
110 if (c == 'l')
111 {
112 try
113 {
114 for (ListenerInterface listener : this.listeners)
115 {
116 System.out.println(listener.getName());
117 continue;
118 }
119 }
120 catch (Exception e)
121 {
122 System.err.println(e.getMessage());
123 continue;
124 }
125 }
126 }
127 s.close();
128 try
129 {
130 RMIUtils.closeRegistry(getRegistry());
131 }
132 catch (Exception re)
133 {
134 System.err.println(re.getMessage());
135 }
136 }
137
138
139
140
141
142 public static void main(final String[] args)
143 {
144 try
145 {
146 Producer producer = new Producer();
147 producer.commands();
148
149 }
150 catch (RemoteException | AlreadyBoundException exception)
151 {
152 exception.printStackTrace();
153 System.exit(-1);
154 }
155 System.exit(0);
156 }
157 }