|
| 1 | +package com.baeldung.jgroups; |
| 2 | + |
| 3 | +import org.apache.commons.cli.*; |
| 4 | +import org.jgroups.*; |
| 5 | +import org.jgroups.util.Util; |
| 6 | + |
| 7 | +import java.io.*; |
| 8 | +import java.util.List; |
| 9 | +import java.util.Optional; |
| 10 | + |
| 11 | +public class JGroupsMessenger extends ReceiverAdapter { |
| 12 | + |
| 13 | + private JChannel channel; |
| 14 | + private String userName; |
| 15 | + private String clusterName; |
| 16 | + private View lastView; |
| 17 | + private boolean running = true; |
| 18 | + |
| 19 | + // Our shared state |
| 20 | + private Integer messageCount = 0; |
| 21 | + |
| 22 | + /** |
| 23 | + * Connect to a JGroups cluster using command line options |
| 24 | + * @param args command line arguments |
| 25 | + * @throws Exception |
| 26 | + */ |
| 27 | + private void start(String[] args) throws Exception { |
| 28 | + processCommandline(args); |
| 29 | + |
| 30 | + // Create the channel |
| 31 | + // This file could be moved, or made a command line option. |
| 32 | + channel = new JChannel("src/main/resources/udp.xml"); |
| 33 | + |
| 34 | + // Set a name |
| 35 | + channel.name(userName); |
| 36 | + |
| 37 | + // Register for callbacks |
| 38 | + channel.setReceiver(this); |
| 39 | + |
| 40 | + // Ignore our messages |
| 41 | + channel.setDiscardOwnMessages(true); |
| 42 | + |
| 43 | + // Connect |
| 44 | + channel.connect(clusterName); |
| 45 | + |
| 46 | + // Start state transfer |
| 47 | + channel.getState(null, 0); |
| 48 | + |
| 49 | + // Do the things |
| 50 | + processInput(); |
| 51 | + |
| 52 | + // Clean up |
| 53 | + channel.close(); |
| 54 | + |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Quick and dirty implementaton of commons cli for command line args |
| 59 | + * @param args the command line args |
| 60 | + * @throws ParseException |
| 61 | + */ |
| 62 | + private void processCommandline(String[] args) throws ParseException { |
| 63 | + |
| 64 | + // Options, parser, friendly help |
| 65 | + Options options = new Options(); |
| 66 | + CommandLineParser parser = new DefaultParser(); |
| 67 | + HelpFormatter formatter = new HelpFormatter(); |
| 68 | + |
| 69 | + options.addOption("u", "user", true, "User name") |
| 70 | + .addOption("c", "cluster", true, "Cluster name"); |
| 71 | + |
| 72 | + CommandLine line = parser.parse(options, args); |
| 73 | + |
| 74 | + if (line.hasOption("user")) { |
| 75 | + userName = line.getOptionValue("user"); |
| 76 | + } else { |
| 77 | + formatter.printHelp("JGroupsMessenger: need a user name.\n", options); |
| 78 | + System.exit(-1); |
| 79 | + } |
| 80 | + |
| 81 | + if (line.hasOption("cluster")) { |
| 82 | + clusterName = line.getOptionValue("cluster"); |
| 83 | + } else { |
| 84 | + formatter.printHelp("JGroupsMessenger: need a cluster name.\n", options); |
| 85 | + System.exit(-1); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + // Start it up |
| 90 | + public static void main(String[] args) throws Exception { |
| 91 | + new JGroupsMessenger().start(args); |
| 92 | + } |
| 93 | + |
| 94 | + |
| 95 | + @Override |
| 96 | + public void viewAccepted(View newView) { |
| 97 | + |
| 98 | + // Save view if this is the first |
| 99 | + if (lastView == null) { |
| 100 | + System.out.println("Received initial view:"); |
| 101 | + newView.forEach(System.out::println); |
| 102 | + } else { |
| 103 | + |
| 104 | + // Compare to last view |
| 105 | + System.out.println("Received new view."); |
| 106 | + |
| 107 | + List<Address> newMembers = View.newMembers(lastView, newView); |
| 108 | + if (newMembers.size() > 0) { |
| 109 | + System.out.println("New members: "); |
| 110 | + newMembers.forEach(System.out::println); |
| 111 | + } |
| 112 | + |
| 113 | + List<Address> exMembers = View.leftMembers(lastView, newView); |
| 114 | + if (exMembers.size() > 0) { |
| 115 | + System.out.println("Exited members:"); |
| 116 | + exMembers.forEach(System.out::println); |
| 117 | + } |
| 118 | + } |
| 119 | + lastView = newView; |
| 120 | + } |
| 121 | + |
| 122 | + /** |
| 123 | + * Loop on console input until we see 'x' to exit |
| 124 | + */ |
| 125 | + private void processInput() { |
| 126 | + |
| 127 | + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); |
| 128 | + while (running) { |
| 129 | + try { |
| 130 | + |
| 131 | + // Get a destination, <enter> means broadcast |
| 132 | + Address destination = null; |
| 133 | + System.out.print("Enter a destination: "); |
| 134 | + System.out.flush(); |
| 135 | + String destinationName = in.readLine().toLowerCase(); |
| 136 | + |
| 137 | + if (destinationName.equals("x")) { |
| 138 | + running = false; |
| 139 | + continue; |
| 140 | + } else if (!destinationName.isEmpty()) { |
| 141 | + Optional<Address> optDestination = getAddress(destinationName); |
| 142 | + if (optDestination.isPresent()) { |
| 143 | + destination = optDestination.get(); |
| 144 | + } else { |
| 145 | + System.out.println("Destination not found, try again."); |
| 146 | + continue; |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + // Accept a string to send |
| 151 | + System.out.print("Enter a message: "); |
| 152 | + System.out.flush(); |
| 153 | + String line = in.readLine().toLowerCase(); |
| 154 | + sendMessage(destination, line); |
| 155 | + } catch (IOException ioe) { |
| 156 | + running = false; |
| 157 | + } |
| 158 | + } |
| 159 | + System.out.println("Exiting."); |
| 160 | + } |
| 161 | + |
| 162 | + /** |
| 163 | + * Send message from here |
| 164 | + * @param destination the destination |
| 165 | + * @param messageString the message |
| 166 | + */ |
| 167 | + private void sendMessage(Address destination, String messageString) { |
| 168 | + try { |
| 169 | + System.out.println("Sending " + messageString + " to " + destination); |
| 170 | + Message message = new Message(destination, messageString); |
| 171 | + channel.send(message); |
| 172 | + } catch (Exception exception) { |
| 173 | + System.err.println("Exception sending message: " + exception.getMessage()); |
| 174 | + running = false; |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + @Override |
| 179 | + public void receive(Message message) { |
| 180 | + // Print source and dest with message |
| 181 | + String line = "Message received from: " + message.getSrc() + " to: " + message.getDest() + " -> " + message.getObject(); |
| 182 | + |
| 183 | + // Only track the count of broadcast messages |
| 184 | + // Tracking direct message would make for a pointless state |
| 185 | + if (message.getDest() == null) { |
| 186 | + messageCount++; |
| 187 | + System.out.println("Message count: " + messageCount); |
| 188 | + } |
| 189 | + |
| 190 | + System.out.println(line); |
| 191 | + } |
| 192 | + |
| 193 | + @Override |
| 194 | + public void getState(OutputStream output) throws Exception { |
| 195 | + // Serialize into the stream |
| 196 | + Util.objectToStream(messageCount, new DataOutputStream(output)); |
| 197 | + } |
| 198 | + |
| 199 | + @Override |
| 200 | + public void setState(InputStream input) { |
| 201 | + |
| 202 | + // NOTE: since we know that incrementing the count and transferring the state |
| 203 | + // is done inside the JChannel's thread, we don't have to worry about synchronizing |
| 204 | + // messageCount. For production code it should be synchronized! |
| 205 | + try { |
| 206 | + // Deserialize |
| 207 | + messageCount = Util.objectFromStream(new DataInputStream(input)); |
| 208 | + } catch (Exception e) { |
| 209 | + System.out.println("Error deserialing state!"); |
| 210 | + } |
| 211 | + System.out.println(messageCount + " is the current messagecount."); |
| 212 | + } |
| 213 | + |
| 214 | + |
| 215 | + private Optional<Address> getAddress(String name) { |
| 216 | + View view = channel.view(); |
| 217 | + return view.getMembers().stream().filter(address -> name.equals(address.toString())).findFirst(); |
| 218 | + } |
| 219 | + |
| 220 | +} |
| 221 | + |
| 222 | + |
0 commit comments