arsovski

Untitled

Jan 3rd, 2021
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.86 KB | None | 0 0
  1. package bg.sofia.uni.fmi.mjt.wish.list;
  2.  
  3. import java.io.IOException;
  4. import java.net.InetSocketAddress;
  5. import java.nio.ByteBuffer;
  6. import java.nio.channels.SelectionKey;
  7. import java.nio.channels.Selector;
  8. import java.nio.channels.ServerSocketChannel;
  9. import java.nio.channels.SocketChannel;
  10.  
  11. import java.util.Map;
  12. import java.util.HashMap;
  13.  
  14. import java.util.Set;
  15. import java.util.HashSet;
  16.  
  17. import java.util.Iterator;
  18.  
  19. import java.util.List;
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22.  
  23. import java.util.Random;
  24. import java.util.stream.Collectors;
  25.  
  26. public class WishListServer {
  27.  
  28. //private static final int SERVER_PORT = 7777;
  29. private int port;
  30. private static final int BUFFER_LIMIT = 1024;
  31. private static final int POST_PARAM_COUNT = 3;
  32. private static final String SERVER_HOST = "localhost";
  33. private static ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_LIMIT);
  34.  
  35.  
  36. private Selector selector;
  37. private static Map<String, Set<String>> wishList = new HashMap<>();
  38.  
  39.  
  40. private boolean isRunning;
  41.  
  42. public WishListServer(int port) {
  43. this.port = port;
  44. isRunning = true;
  45. }
  46.  
  47.  
  48. public void start() {
  49. try (ServerSocketChannel serverChannel = ServerSocketChannel.open();
  50. ) {
  51.  
  52. serverChannel.bind(new InetSocketAddress(SERVER_HOST, port));
  53. serverChannel.configureBlocking(false);
  54.  
  55. selector = Selector.open();
  56. serverChannel.register(selector, SelectionKey.OP_ACCEPT);
  57.  
  58. while (this.isRunning) {
  59. int readyChannels = selector.select();
  60. if (readyChannels == 0) {
  61. continue; // no channels
  62. }
  63.  
  64. Set<SelectionKey> keys = selector.selectedKeys();
  65. Iterator<SelectionKey> iterator = keys.iterator();
  66.  
  67. while (iterator.hasNext()) {
  68. SelectionKey key = iterator.next();
  69.  
  70. if (key.isAcceptable()) {
  71. ServerSocketChannel socketChannel = (ServerSocketChannel) key.channel();
  72. SocketChannel clientSocket = socketChannel.accept();
  73. clientSocket.configureBlocking(false);
  74. clientSocket.register(selector, SelectionKey.OP_READ);
  75. } else if (key.isReadable()) {
  76.  
  77.  
  78. SocketChannel clientChannel = (SocketChannel) key.channel();
  79.  
  80. buffer.clear();
  81. int rd = clientChannel.read(buffer);
  82. if (rd < 0) {
  83. System.out.println("client stopped communication");
  84. clientChannel.close();
  85. continue;
  86. }
  87.  
  88. buffer.flip();
  89.  
  90. // parse the buffer
  91. String serverResponse = "[ Unknown command ]";
  92.  
  93. // Convert buffer to String
  94.  
  95. byte[] byteArray = new byte[buffer.remaining()];
  96. buffer.get(byteArray);
  97. String reply = new String(byteArray, "UTF-8"); // buffer drain
  98.  
  99. List<String> parsedBuffer = Arrays.asList(reply.split(" "));
  100. String commandName = parsedBuffer.get(0).toLowerCase();
  101.  
  102. if (commandName.equals("post-wish")) {
  103. if (parsedBuffer.size() < POST_PARAM_COUNT) {
  104. serverResponse = "[ Unknown command ]";
  105. }
  106.  
  107. String gift = String.join(" ", parsedBuffer.subList(2, parsedBuffer.size()));
  108.  
  109. if (gift.isEmpty()) {
  110. serverResponse = "[ Unknown command ]";
  111. }
  112.  
  113. serverResponse = postWish(parsedBuffer.get(1),
  114. gift.toLowerCase());
  115. } else if (commandName.equals("get-wish")) {
  116. serverResponse = getWish();
  117. } else if (commandName.equals("disconnect")) {
  118. serverResponse = "[ Disconnected from server ]";
  119.  
  120. serverResponse = serverResponse + System.lineSeparator();
  121.  
  122. buffer.clear();
  123. buffer.put(serverResponse.getBytes("UTF-8"));
  124.  
  125. buffer.flip();
  126. clientChannel.write(buffer);
  127.  
  128. clientChannel.close();
  129. continue;
  130. }
  131.  
  132.  
  133. // Response
  134. serverResponse = serverResponse + System.lineSeparator();
  135.  
  136. buffer.clear();
  137. buffer.put(serverResponse.getBytes("UTF-8"));
  138.  
  139. buffer.flip();
  140. clientChannel.write(buffer);
  141.  
  142. }
  143.  
  144. iterator.remove(); // remove answered response
  145. }
  146. }
  147.  
  148. } catch (
  149. IOException e) {
  150. System.out.println("Problem establishing connection ..");
  151. e.printStackTrace();
  152. }
  153.  
  154. }
  155.  
  156. private static String postWish(String username, String gift) {
  157. String result = "[ Gift " + gift + " for student " + username
  158. + " submitted successfully ]";
  159. if (!wishList.containsKey(username)) {
  160. wishList.put(username, new HashSet<>());
  161. wishList.get(username).add(gift);
  162. } else {
  163. // if it gift is already present
  164. if (wishList.get(username).contains(gift)) {
  165. result = "[ The same gift for student " + username + " was already submitted ]";
  166. } else {
  167. wishList.get(username).add(gift);
  168. }
  169. }
  170.  
  171.  
  172. return result;
  173.  
  174. }
  175.  
  176. private static String getWish() {
  177.  
  178. if (wishList.isEmpty()) {
  179. return "[ There are no students present in the wish list ]";
  180. }
  181.  
  182. // Get random user from hashMap and print its wishes
  183.  
  184. // Get random user name from HashMap
  185.  
  186. List<String> users = new ArrayList<>(wishList.keySet());
  187. Random random = new Random();
  188.  
  189. String randomUser = users.get(random.nextInt(users.size()));
  190.  
  191. Set<String> gifts = wishList.get(randomUser);
  192. wishList.remove(randomUser);
  193.  
  194. return "[ " + randomUser + ": " + gifts + " ]";
  195.  
  196.  
  197. }
  198.  
  199. public void stop() {
  200. this.isRunning = false;
  201.  
  202. try {
  203. selector.close();
  204. } catch (IOException e) {
  205. System.out.println("Failed to close selector");
  206. e.printStackTrace();
  207. }
  208. }
  209.  
  210. }
  211.  
Advertisement
Add Comment
Please, Sign In to add comment