Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package bg.sofia.uni.fmi.mjt.wish.list;
- import java.io.IOException;
- import java.net.InetSocketAddress;
- import java.nio.ByteBuffer;
- import java.nio.channels.SelectionKey;
- import java.nio.channels.Selector;
- import java.nio.channels.ServerSocketChannel;
- import java.nio.channels.SocketChannel;
- import java.util.Map;
- import java.util.HashMap;
- import java.util.Set;
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.List;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Random;
- import java.util.stream.Collectors;
- public class WishListServer {
- //private static final int SERVER_PORT = 7777;
- private int port;
- private static final int BUFFER_LIMIT = 1024;
- private static final int POST_PARAM_COUNT = 3;
- private static final String SERVER_HOST = "localhost";
- private static ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_LIMIT);
- private Selector selector;
- private static Map<String, Set<String>> wishList = new HashMap<>();
- private boolean isRunning;
- public WishListServer(int port) {
- this.port = port;
- isRunning = true;
- }
- public void start() {
- try (ServerSocketChannel serverChannel = ServerSocketChannel.open();
- ) {
- serverChannel.bind(new InetSocketAddress(SERVER_HOST, port));
- serverChannel.configureBlocking(false);
- selector = Selector.open();
- serverChannel.register(selector, SelectionKey.OP_ACCEPT);
- while (this.isRunning) {
- int readyChannels = selector.select();
- if (readyChannels == 0) {
- continue; // no channels
- }
- Set<SelectionKey> keys = selector.selectedKeys();
- Iterator<SelectionKey> iterator = keys.iterator();
- while (iterator.hasNext()) {
- SelectionKey key = iterator.next();
- if (key.isAcceptable()) {
- ServerSocketChannel socketChannel = (ServerSocketChannel) key.channel();
- SocketChannel clientSocket = socketChannel.accept();
- clientSocket.configureBlocking(false);
- clientSocket.register(selector, SelectionKey.OP_READ);
- } else if (key.isReadable()) {
- SocketChannel clientChannel = (SocketChannel) key.channel();
- buffer.clear();
- int rd = clientChannel.read(buffer);
- if (rd < 0) {
- System.out.println("client stopped communication");
- clientChannel.close();
- continue;
- }
- buffer.flip();
- // parse the buffer
- String serverResponse = "[ Unknown command ]";
- // Convert buffer to String
- byte[] byteArray = new byte[buffer.remaining()];
- buffer.get(byteArray);
- String reply = new String(byteArray, "UTF-8"); // buffer drain
- List<String> parsedBuffer = Arrays.asList(reply.split(" "));
- String commandName = parsedBuffer.get(0).toLowerCase();
- if (commandName.equals("post-wish")) {
- if (parsedBuffer.size() < POST_PARAM_COUNT) {
- serverResponse = "[ Unknown command ]";
- }
- String gift = String.join(" ", parsedBuffer.subList(2, parsedBuffer.size()));
- if (gift.isEmpty()) {
- serverResponse = "[ Unknown command ]";
- }
- serverResponse = postWish(parsedBuffer.get(1),
- gift.toLowerCase());
- } else if (commandName.equals("get-wish")) {
- serverResponse = getWish();
- } else if (commandName.equals("disconnect")) {
- serverResponse = "[ Disconnected from server ]";
- serverResponse = serverResponse + System.lineSeparator();
- buffer.clear();
- buffer.put(serverResponse.getBytes("UTF-8"));
- buffer.flip();
- clientChannel.write(buffer);
- clientChannel.close();
- continue;
- }
- // Response
- serverResponse = serverResponse + System.lineSeparator();
- buffer.clear();
- buffer.put(serverResponse.getBytes("UTF-8"));
- buffer.flip();
- clientChannel.write(buffer);
- }
- iterator.remove(); // remove answered response
- }
- }
- } catch (
- IOException e) {
- System.out.println("Problem establishing connection ..");
- e.printStackTrace();
- }
- }
- private static String postWish(String username, String gift) {
- String result = "[ Gift " + gift + " for student " + username
- + " submitted successfully ]";
- if (!wishList.containsKey(username)) {
- wishList.put(username, new HashSet<>());
- wishList.get(username).add(gift);
- } else {
- // if it gift is already present
- if (wishList.get(username).contains(gift)) {
- result = "[ The same gift for student " + username + " was already submitted ]";
- } else {
- wishList.get(username).add(gift);
- }
- }
- return result;
- }
- private static String getWish() {
- if (wishList.isEmpty()) {
- return "[ There are no students present in the wish list ]";
- }
- // Get random user from hashMap and print its wishes
- // Get random user name from HashMap
- List<String> users = new ArrayList<>(wishList.keySet());
- Random random = new Random();
- String randomUser = users.get(random.nextInt(users.size()));
- Set<String> gifts = wishList.get(randomUser);
- wishList.remove(randomUser);
- return "[ " + randomUser + ": " + gifts + " ]";
- }
- public void stop() {
- this.isRunning = false;
- try {
- selector.close();
- } catch (IOException e) {
- System.out.println("Failed to close selector");
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment