+/EE360P

distributed systems

git clone https://git.julia.blue/+/EE360P

Joseph RyanAdd exit command handling73968d3

master
6.6 KiB187 linesraw
1import java.io.*;
2import java.net.*;
3import java.util.*;
4import java.util.Map.Entry;
5import java.util.concurrent.atomic.*;
6import java.util.concurrent.locks.*;
7
8public class BookServer {
9    static LinkedHashMap<String, AtomicInteger> books;
10    static HashMap<Integer, String> checkedOut;
11    static HashMap<String, HashSet<Integer>> students;
12    static ServerSocket tcpSocket;
13    static DatagramSocket udpSocket;
14    static ReentrantLock lock;
15    static int bookID = 1;
16
17    public static void main(String[] args) throws Exception {
18        final int tcpPort = 7000;
19        final int udpPort = 8000;
20        if (args.length != 1) {
21            System.out.println(
22                "ERROR: Provide 1 argument: input file containing initial inventory");
23            System.exit(-1);
24        }
25        books = new LinkedHashMap<>();
26        checkedOut = new LinkedHashMap<>();
27        students = new LinkedHashMap<>();
28        lock = new ReentrantLock();
29
30        try {
31            BufferedReader reader = new BufferedReader(new FileReader(args[0]));
32            String line = reader.readLine();
33            while (line != null) {
34                int quote = line.lastIndexOf('"');
35                books.put(line.substring(0, quote + 1),
36                          new AtomicInteger(
37                              Integer.parseInt(line.substring(quote + 2))));
38                line = reader.readLine();
39            }
40            reader.close();
41        } catch (IOException e) { e.printStackTrace(); }
42
43        System.out.println("Initial book count:");
44        for (Entry e : books.entrySet()) { System.out.println("  " + e); }
45
46        tcpSocket = new ServerSocket(tcpPort);
47        udpSocket = new DatagramSocket(udpPort);
48
49        new Thread(() -> {
50            while (true) {
51                try {
52                    new Thread(new TcpHandler(tcpSocket.accept())).start();
53                } catch (Exception e) {}
54            }
55        }).start();
56
57        new Thread(() -> {
58            byte[] buf = new byte[1 << 15];
59            DatagramPacket packet;
60            while (true) {
61                try {
62                    packet = new DatagramPacket(buf, buf.length);
63                    udpSocket.receive(packet);
64                    new Thread(new UdpHandler(udpSocket, packet)).start();
65                } catch (Exception e) {}
66            }
67        }).start();
68    }
69
70    static String handleCommand(String s) {
71        String[] parts = s.split("\\|");
72        switch (parts[0].charAt(0)) {
73        case 's':
74            return "The communication mode is set to " +
75                (parts[1].charAt(0) == 'T' ? "TCP" : "UDP");
76        case 'b':
77            String student = parts[1];
78            String book = parts[2];
79            AtomicInteger count = books.get(book);
80            if (count == null) {
81                return "Request Failed - We do not have this book";
82            }
83            lock.lock();
84            if (count.get() == 0) {
85                lock.unlock();
86                return "Request Failed - Book not available";
87            }
88            count.getAndDecrement();
89            HashSet<Integer> ids = students.get(student);
90            if (ids == null) {
91                ids = new HashSet<>();
92                students.put(student, ids);
93            }
94            ids.add(bookID);
95            checkedOut.put(bookID, book);
96            lock.unlock();
97            return "Your request has been approved, " + bookID++ + " " +
98                student + " " + book;
99        case 'r':
100            int id = Integer.parseInt(parts[1]);
101            lock.lock();
102            book = checkedOut.remove(id);
103            if (book == null) {
104                lock.unlock();
105                return "" + id + " not found, no such borrow record";
106            }
107            for (HashSet<Integer> temp : students.values()) { temp.remove(id); }
108            books.get(book).getAndIncrement();
109            lock.unlock();
110            return "" + id + " is returned";
111        case 'l':
112            student = parts[1];
113            lock.lock();
114            ids = students.get(student);
115            if (ids == null) {
116                lock.unlock();
117                return "No record found for " + student;
118            }
119            String result = "";
120            for (Integer i : ids) {
121                if (result.length() > 0) { result += "|"; }
122                result += i + " " + checkedOut.get(i);
123            }
124            lock.unlock();
125            return result;
126        case 'i':
127            result = "";
128            lock.lock();
129            for (Entry e : books.entrySet()) {
130                if (result.length() > 0) { result += "|"; }
131                result += e.getKey() + " " + e.getValue();
132            }
133            lock.unlock();
134            return result;
135        case 'e': 
136            PrintWriter out = null;
137            try { out = new PrintWriter("inventory.txt");
138            } catch (Exception e) {e.printStackTrace();}
139            for (Entry e : books.entrySet()) {
140                out.println(e.getKey() + " " + e.getValue());
141            }
142            out.close();
143        }
144        return "RIP";
145    }
146
147    static class TcpHandler implements Runnable {
148        Socket socket;
149        public TcpHandler(Socket socket) { this.socket = socket; }
150        public void run() {
151            try {
152                BufferedReader in = new BufferedReader(
153                    new InputStreamReader(socket.getInputStream()));
154                PrintWriter out =
155                    new PrintWriter(socket.getOutputStream(), true);
156                String command = in.readLine();
157                while (command != null) {
158                    out.println(handleCommand(command));
159                    System.out.println();
160                    System.out.println("Books: " + books);
161                    System.out.println("Students: " + students);
162                    System.out.println("Checkedout: " + checkedOut);
163                    command = in.readLine();
164                }
165            } catch (Exception e) { // e.printStackTrace();
166            }
167        }
168    }
169
170    static class UdpHandler implements Runnable {
171        DatagramSocket socket;
172        DatagramPacket packet;
173        public UdpHandler(DatagramSocket socket, DatagramPacket packet) {
174            this.socket = socket;
175            this.packet = packet;
176        }
177        public void run() {
178            try {
179                packet.getData();
180                String command =
181                    new String(packet.getData(), 0, packet.getLength());
182                packet.setData(handleCommand(command).getBytes("UTF-8"));
183                udpSocket.send(packet);
184            } catch (Exception e) { e.printStackTrace(); }
185        }
186    }
187}