Advertisement
StefanTodorovski

(Java) OS: Lab 3 - ОС: Лаб 3

Apr 4th, 2019
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 54.64 KB | None | 0 0
  1. /*
  2. Task 1 Problem 1 (1 / 1)
  3. You are hired by the show „Dancing with the students“, in order to implement a software solution which will automatically control the gates which guide the contestants.
  4.  
  5. The entry gate leads directly to one of the changing rooms, where the contestants should change their clothes. You can have at most 10 contestants in each changing room, at the same time.
  6.  
  7. After they change, the contestants wait for a random partner from the opposite gender, after which they exit the changing room and enter the dancing room. The dancing room can have a maximum of three pairs dancing at the same time (in parallel). After they finish dancing, the pairs exit the dancing room leaving space for a new pair to enter and start dancing.
  8.  
  9. In the starter code, you have the definition of two classes, Masko (Male) and Zensko (Female), which represent contestants from the corresponding gender. Each of the classes has multiple running instances, and each instance can dance only once.
  10.  
  11. In your implementation, you can use the following methods from show:
  12.  
  13. show.presobleci()
  14. Represents a contestant entering in the changing room and changing
  15. Cannot be called in parallel by more than 10 contestants from the same gender
  16. show.tancuvaj()
  17. Represents the start of the dance
  18. Can only be called by male contestants, as they lead the dance
  19. The male contestant should make sure that a female contestant is present as his partner before he makes the call
  20. There cannot be more than 3 parallel calls on this method
  21. These methods manipulate with a shared resource and are not atomic.
  22.  
  23. Your task is to implement the methods Masko.ucestvo(), Zensko.ucestvo() and init(). In your implementation, you can not add try-catch blocks in them. You should define the necessary semaphores, global variables and state variables.
  24.  
  25. If you have an error, you will get this message:
  26.  
  27. Procesot ne e sinhroniziran spored uslovite na zadacata // The process in not synchronized according to the conditions in the task
  28.  
  29. After that you will see the log of actions and errors. Use this log to see what went wrong,
  30.  
  31. Note: Due to concurrent execution of the logging, it is possible that some of the messages in the log are not in the position they are supposed to be. Therefore, use them only as guideline information, do not base all of the conclusions on them.
  32. */
  33.  
  34. import java.util.ArrayList;
  35. import java.util.HashSet;
  36. import java.util.List;
  37. import java.util.Random;
  38. import java.util.concurrent.Semaphore;
  39.  
  40. public class TancSoStudentite {
  41.     //TODO: Definicija na globalni promenlivi i semafori
  42.     private static Semaphore enterMaleChangingRoom;
  43.     private static Semaphore enterFemaleChangingRoom;
  44.     private static Semaphore enterDancingRoom;
  45.     private static Semaphore readyFemales;
  46.     private static Semaphore readyToDance;
  47.  
  48.  
  49.     public void init() {
  50.         //TODO: da se implementira
  51.         enterMaleChangingRoom = new Semaphore(10);
  52.         enterFemaleChangingRoom = new Semaphore(10);
  53.         enterDancingRoom = new Semaphore(3);
  54.         readyFemales = new Semaphore(0);
  55.         readyToDance = new Semaphore(0);
  56.     }
  57.  
  58.     class Masko extends Thread {
  59.         //TODO: Definicija  na promenlivi za sostojbata
  60.  
  61.         public void ucestvo() throws InterruptedException {
  62.             //TODO: da se implementira
  63.             enterMaleChangingRoom.acquire();
  64.             show.presobleci();
  65.             readyFemales.acquire();
  66.             // samo maskoto go povikuva metodot tancuvaj
  67.             readyToDance.release();
  68.             enterMaleChangingRoom.release();
  69.  
  70.             enterDancingRoom.acquire();
  71.             show.tancuvaj();
  72.             enterDancingRoom.release();
  73.         }
  74.  
  75.         @Override
  76.         public void run() {
  77.             try {
  78.                 ucestvo();
  79.             } catch (InterruptedException e) {
  80.                 // Do nothing
  81.             } catch (Exception e) {
  82.                 exception = e;
  83.                 hasException = true;
  84.             }
  85.         }
  86.  
  87.         @Override
  88.         public String toString() {
  89.             return String.format("m\t%d", getId());
  90.         }
  91.         public Exception exception = null;
  92.     }
  93.  
  94.     class Zensko extends Thread {
  95.         //TODO: Definicija  na promenlivi za sostojbata
  96.  
  97.         public void ucestvo() throws InterruptedException {
  98.             //TODO: da se implementira
  99.             enterFemaleChangingRoom.acquire();
  100.             show.presobleci();
  101.             readyFemales.release();
  102.             readyToDance.acquire();
  103.             enterFemaleChangingRoom.release();
  104.         }
  105.  
  106.         @Override
  107.         public void run() {
  108.             try {
  109.                 ucestvo();
  110.             } catch (InterruptedException e) {
  111.                 // Do nothing
  112.             } catch (Exception e) {
  113.                 exception = e;
  114.                 hasException = true;
  115.             }
  116.         }
  117.  
  118.         @Override
  119.         public String toString() {
  120.             return String.format("z\t%d", getId());
  121.         }
  122.         public Exception exception = null;
  123.     }
  124.  
  125.     public static void main(String[] args) {
  126.         try {
  127.             TancSoStudentite environment = new TancSoStudentite();
  128.             environment.start();
  129.         } catch (Exception ex) {
  130.             ex.printStackTrace();
  131.         }
  132.     }
  133.  
  134.     public void start() throws Exception {
  135.         show = new Show();
  136.         init();
  137.         HashSet<Thread> threads = new HashSet<Thread>();
  138.         for (int i = 0; i < BROJ_INSTANCI; i++) {
  139.             Zensko z = new Zensko();
  140.             Masko m = new Masko();
  141.             threads.add(z);
  142.             threads.add(m);
  143.         }
  144.  
  145.         for (Thread t : threads) {
  146.             t.start();
  147.         }
  148.  
  149.         boolean valid = true;
  150.         for (Thread t : threads) {
  151.             if (!hasException) {
  152.                 t.join();
  153.             } else {
  154.                 t.interrupt();
  155.             }
  156.         }
  157.         show.printStatus();
  158.  
  159.     }
  160.  
  161.     public class Show {
  162.  
  163.         public static final int BROJ_GARDEROBA = 10;
  164.         public static final int BROJ_TEREN = 3;
  165.         public static final int TYPE_MASKO = 1;
  166.         public static final int TYPE_ZENSKO = 2;
  167.         public static final int TYPE_UNKNOWN = -1;
  168.  
  169.         public Show() {
  170.         }
  171.         public int brojMaskiGarderoba = 0;
  172.         public int brojZenskiGarderoba = 0;
  173.         public int brojTancuvanja = 0;
  174.         public int maxMaskiGarderoba = 0;
  175.         public int maxZenskiGarderoba = 0;
  176.         public int maxTancuvanja = 0;
  177.  
  178.         public void presobleci() throws RuntimeException {
  179.             log(null, "presobleci start");
  180.             Thread t = Thread.currentThread();
  181.             if (t instanceof Masko) {
  182.                 synchronized (RANDOM) {
  183.                     brojMaskiGarderoba++;
  184.                     if (brojMaskiGarderoba > 10) {
  185.                         exception("Ne moze da ima poveke od 10 maski vo maskata garderoba.");
  186.                     }
  187.                     if (brojMaskiGarderoba > maxMaskiGarderoba) {
  188.                         maxMaskiGarderoba = brojMaskiGarderoba;
  189.                     }
  190.                 }
  191.                 waitRandom();
  192.                 synchronized (RANDOM) {
  193.                     brojMaskiGarderoba--;
  194.                 }
  195.             } else {
  196.                 synchronized (RANDOM) {
  197.                     brojZenskiGarderoba++;
  198.                     if (brojZenskiGarderoba > 10) {
  199.                         exception("Ne moze da ima poveke od 10 zenski vo zenskata garderoba.");
  200.                     }
  201.                     if (brojZenskiGarderoba > maxZenskiGarderoba) {
  202.                         maxZenskiGarderoba = brojZenskiGarderoba;
  203.                     }
  204.                 }
  205.                 waitRandom();
  206.                 synchronized (RANDOM) {
  207.                     brojZenskiGarderoba--;
  208.                 }
  209.             }
  210.             log(null, "presobleci kraj");
  211.         }
  212.  
  213.         public void tancuvaj() throws RuntimeException {
  214.             log(null, "tancuvaj start");
  215.             synchronized (RANDOM) {
  216.                 brojTancuvanja++;
  217.                 if (brojTancuvanja > BROJ_TEREN) {
  218.                     exception("Ne moze paralelno da tancuvaat poveke od 3 para.");
  219.                 }
  220.  
  221.                 if (brojTancuvanja > maxTancuvanja) {
  222.                     maxTancuvanja = brojTancuvanja;
  223.                 }
  224.             }
  225.             waitRandom();
  226.             synchronized (RANDOM) {
  227.                 brojTancuvanja--;
  228.             }
  229.             log(null, "tancuvaj kraj");
  230.         }
  231.  
  232.         private void waitRandom() {
  233.             try {
  234.                 int r;
  235.                 synchronized (RANDOM) {
  236.                     r = RANDOM.nextInt(RANDOM_RANGE);
  237.                 }
  238.                 Thread.sleep(r);
  239.             } catch (Exception e) {
  240.                 //do nothing
  241.             }
  242.         }
  243.  
  244.         private void exception(String message) {
  245.             RuntimeException e = new RuntimeException(message);
  246.             log(e, null);
  247.             hasError = true;
  248.             throw e;
  249.         }
  250.  
  251.         public int getType() {
  252.             Thread t = Thread.currentThread();
  253.             if (t instanceof Masko) {
  254.                 return TYPE_MASKO;
  255.             } else if (t instanceof Zensko) {
  256.                 return TYPE_ZENSKO;
  257.             } else {
  258.                 return TYPE_UNKNOWN;
  259.             }
  260.         }
  261.  
  262.         private synchronized void log(RuntimeException e, String action) {
  263.             Thread t = Thread.currentThread();
  264.             if (e == null) {
  265.                 actions.add(t.toString() + "\t(a): " + action);
  266.             } else {
  267.                 actions.add(t.toString() + "\t(e): " + e.getMessage());
  268.             }
  269.         }
  270.  
  271.         public synchronized void printLog() {
  272.             System.out.println("Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
  273.             System.out.println("Log na izvrsuvanje na akciite:");
  274.             System.out.println("=========================");
  275.             System.out.println("(tip m<=>Masko, tip z<=>Zensko)");
  276.             System.out.println("tip\tid\takcija/error");
  277.             System.out.println("=========================");
  278.             for (String l : actions) {
  279.                 System.out.println(l);
  280.             }
  281.         }
  282.  
  283.         public void printStatus() {
  284.             if (!hasError) {
  285.                 int poeni = 25;
  286.                 System.out.println("Procesot e uspesno sinhroniziran");
  287.                 if (show.maxMaskiGarderoba == 1 || show.maxZenskiGarderoba == 1) {
  288.                     System.out.println("\t-no ima maksimum eden ucesnik vo garderobata.");
  289.                     poeni -= 5;
  290.                 }
  291.                 if (show.maxTancuvanja == 1) {
  292.                     System.out.println("\t-no ima maksimum edna proverka vo eden moment.");
  293.                     poeni -= 5;
  294.                 }
  295.  
  296.                 System.out.println("Osvoeni poeni: " + poeni);
  297.  
  298.             } else {
  299.                 System.out.println("Procesot ne e sinhroniziran spored uslovite na zadacata");
  300.                 show.printLog();
  301.                 System.out.println("Maksimum mozni poeni: 15");
  302.             }
  303.  
  304.         }
  305.         private List<String> actions = new ArrayList<String>();
  306.         private boolean hasError = false;
  307.     }
  308.     // Konstanti
  309.     public static int BROJ_INSTANCI = 1000;
  310.     public static final Random RANDOM = new Random();
  311.     public static final int RANDOM_RANGE = 3;
  312.     // Instanca od bafferot
  313.     public Show show;
  314.     public boolean hasException = false;
  315. }
  316.  
  317.  
  318.  
  319.  
  320.  
  321.  
  322. /*
  323. Task 2 Problem 1 (1 / 1)
  324. You need to synchronize the scenario of a barber shop. The barber shop has only one barber who sleeps until there are 5 clients waiting. After 5 clients are present, the fifth one wakes the barber up and he starts to give them haircuts. Once the barber serves all of the clients which are waiting, he falls asleep, again.
  325.  
  326. When the barber is awake, he calls one client to enter his barber shop. After the client enters, the hair-cutting begins. Once the client has been served, he pays and leaves the barber shop, allowing the next client to enter. If there is no other client present, the barber will go to sleep. If the barber is sleeping, the clients have to wait until they are 5, and the fifth one should wake the barber up.
  327.  
  328. In the starter code you have the Barber and Customer classes, which represent the barber and the clients. There is only one Barber instance, which calls the execute() method as many times as there are clients in the scenario. There are multiple Customer instances, which call the execute() method only once.
  329.  
  330. You task is to implement the execute() methods in the Barber and Customer classes, according to the scenario above.
  331.  
  332. In your implementation, you can use the following methods which already exist in state:
  333.  
  334. state.customerArrived()
  335. Represents the arrival of the client in front of the barber shop. It's called by the client, upon his arrival.
  336. state.barberWakeUp()
  337. Represents the waking up of the barber. It is called by the barber, when he wakes up.
  338. If the barber is already awake, the call will throw an exception
  339. state.barberCallCustomer()
  340. Represents the client being called by the barber. The method is called by the barber.
  341. If there is no client which has arrived, the call will throw an exception.
  342. state.customerEntry()
  343. Represents the client entering the barber shop. It is called by the client.
  344. If there is no client present, or there has not been a call by the barber, it will throw an exception.
  345. state.cutHair()
  346. Represents the hair-cutting process by the barber. It's called by the barber.
  347. If there is no client present inside the barber shop, it will throw an exception
  348. state.customerPay()
  349. Represents the payment by the client, as he leaves the barber shop. It's called by the client.
  350. state.barberGoToSleep()
  351. Represents the barber going to sleep, when there are no clients present. It is called by the barber.
  352. If the barber is already asleep or there are no waiting clients, it will throw an exception.
  353. These methods are used for validation the scenario and cannot be changed. They need to be called.
  354.  
  355. Your task is to implement the methods Barber.execute(), Customer.execute() and init(). In your implementation, you can not add try-catch blocks in them. You should define the necessary semaphores and other variables.
  356.  
  357. If you have an error, you will get this message:
  358.  
  359. Procesot ne e sinhroniziran spored uslovite na zadacata // The process in not synchronized according to the conditions in the task
  360.  
  361. After that you will see the log of actions and errors. Use this log to see what went wrong,
  362.  
  363. Note: Due to concurrent execution of the logging, it is possible that some of the messages in the log are not in the position they are supposed to be. Therefore, use them only as guideline information, do not base all of the conclusions on them.
  364. */
  365.  
  366. import java.util.ArrayList;
  367. import java.util.HashMap;
  368. import java.util.HashSet;
  369. import java.util.List;
  370. import java.util.Map;
  371. import java.util.Random;
  372. import java.util.Scanner;
  373. import java.util.concurrent.Semaphore;
  374.  
  375. public class TemplateNumRunsAndNumInstances {
  376.  
  377.     /*
  378.     INPUT:
  379.     1
  380.     100
  381.     1
  382.     1
  383.      */
  384.  
  385.     //TODO: definirajte gi semaforite i ostanatite promenlivi ovde (mora site da se static)
  386.     private static int customersWaiting;
  387.     private static Object customerWaitingLock;
  388.     private static Semaphore enterShop;
  389.     private static Semaphore barberWorking;
  390.     private static Semaphore barberFinishedCutting;
  391.     private static Semaphore clientSit;
  392.     private static Semaphore customerPaid;
  393.  
  394.     /**
  395.      * Metod koj treba da gi inicijalizira vrednostite na semaforite i
  396.      * ostanatite promenlivi za sinhronizacija.
  397.      *
  398.      *
  399.      * TODO: da se implementira
  400.      *
  401.      */
  402.     public static void init(int numBarbers) {
  403.         customersWaiting = 0;
  404.         customerWaitingLock = new Object();
  405.         enterShop = new Semaphore(0);
  406.         barberWorking = new Semaphore(0);
  407.         barberFinishedCutting = new Semaphore(0);
  408.         clientSit = new Semaphore(0);
  409.         customerPaid = new Semaphore(0);
  410.     }
  411.  
  412.     static class Barber extends TemplateThread {
  413.  
  414.         public int barberId;
  415.  
  416.         public Barber(int numRuns, int barberId) {
  417.             super(numRuns);
  418.             this.barberId = barberId;
  419.         }
  420.  
  421.         /**
  422.          * Da se implementira odnesuvanjeto na berberot spored baranjeto na
  423.          * zadacata.
  424.          *
  425.          *
  426.          * TODO: da se implementira
  427.          *
  428.          */
  429.         public void execute() throws InterruptedException {
  430.             // koga 5tiot klient ke notificira, berberot treba da se razbudi
  431.             barberWorking.acquire();
  432.             state.barberWakeUp();
  433.  
  434.             // koga klientot ke pristigne, go vika klientot da vleze
  435.             while(true) {
  436.                 state.barberCallCustomer();
  437.                 enterShop.release();
  438.  
  439.                 // koga klientot ke vleze, go potstrizuva
  440.                 clientSit.acquire();
  441.                 state.cutHair();
  442.  
  443.                 barberFinishedCutting.release();
  444.                 customerPaid.acquire();
  445.                 synchronized(customerWaitingLock) {
  446.                     customersWaiting--;
  447.  
  448.                     // proveruva dali ima klienti koi cekaat, ako nema, zaspiva
  449.                     if(customersWaiting <= 0) {
  450.                         state.barberGoToSleep();
  451.                         barberWorking.acquire();
  452.                     }
  453.                 }
  454.             }
  455.         }
  456.     }
  457.  
  458.     static class Consumer extends TemplateThread {
  459.  
  460.         public Consumer(int numRuns) {
  461.             super(numRuns);
  462.         }
  463.  
  464.         /**
  465.          * Da se implementira odnesuvanjeto na ucesnikot spored uslovite na
  466.          * zadacata.
  467.          */
  468.         public void execute() throws InterruptedException {
  469.             synchronized(customerWaitingLock) {
  470.                 state.customerArrived();
  471.                 customersWaiting++;
  472.                 // dokolku e pettiot, go budi berberot
  473.                 if(customersWaiting == 5 && !state.barberWaked[0]) {
  474.                     barberWorking.release();
  475.                 }
  476.             }
  477.             // koga ke bide povikan, vleguva
  478.             enterShop.acquire();
  479.             state.customerEntry();
  480.             clientSit.release();
  481.             barberFinishedCutting.acquire();
  482.             // klientot vlegol vo berbernicata i e spremen za potstrizuvanje
  483.             // koga ke go potstrizat, plakja
  484.             state.customerPay();
  485.             customerPaid.release();
  486.         }
  487.     }
  488.     //<editor-fold defaultstate="collapsed" desc="This is the template code" >
  489.     static State state;
  490.  
  491.     static class State {
  492.  
  493.         private static final Random RANDOM = new Random();
  494.         private static final int RANDOM_RANGE = 5;
  495.         private final int numBarbers;
  496.         private boolean barberWaked[];
  497.  
  498.         public State(int numBarbers) {
  499.             this.numBarbers = numBarbers;
  500.             barberWaked = new boolean[numBarbers];
  501.         }
  502.         private int arrivedCustomers = 0;
  503.         private int calledCustomers = 0;
  504.         private int maxCuttings = 0;
  505.         private int numCuttings = 0;
  506.  
  507.         public synchronized void customerArrived() throws RuntimeException {
  508.             log(null, "customer arrived");
  509.             arrivedCustomers++;
  510.         }
  511.  
  512.         public synchronized void barberWakeUp() {
  513.             Barber b = (Barber) Thread.currentThread();
  514.             if (barberWaked[b.barberId]) {
  515.                 PointsException e = new PointsException(5, "Berberot e veke buden i nema potreba da se razbudi.");
  516.                 log(e, null);
  517.             } else {
  518.                 log(null, "the barber is waked up");
  519.                 barberWaked[b.barberId] = true;
  520.             }
  521.         }
  522.  
  523.         public synchronized void barberCallCustomer() throws RuntimeException {
  524.             log(null, "the barber calls the customer");
  525.             if (arrivedCustomers <= 0) {
  526.                 PointsException e = new PointsException(5, "Brojot na klienti koi cekaat e 0 i nema koj da bide povikan.");
  527.                 log(e, null);
  528.             }
  529.             calledCustomers++;
  530.         }
  531.  
  532.         public synchronized void customerEntry() throws RuntimeException {
  533.             log(null, "customer sits in the chair");
  534.             if (arrivedCustomers <= 0) {
  535.                 PointsException e = new PointsException(5, "Brojot na klienti koi cekaat e 0 i nema koj da vleze.");
  536.                 log(e, null);
  537.             }
  538.             if (calledCustomers <= 0) {
  539.                 PointsException e = new PointsException(5, "Nema povikano klient i ne moze da vleze.");
  540.                 log(e, null);
  541.             }
  542.             arrivedCustomers--;
  543.             calledCustomers--;
  544.  
  545.             numCuttings++;
  546.         }
  547.  
  548.         public void cutHair() throws RuntimeException {
  549.             synchronized (this) {
  550.                 if (numCuttings <= 0) {
  551.                     PointsException e = new PointsException(5, "Nema prisuten klient za potstrizuvanje");
  552.                     log(e, null);
  553.                 }
  554.  
  555.                 log(null, "berber cuts the customer hair");
  556.             }
  557.             try {
  558.                 int r;
  559.                 synchronized (this) {
  560.                     r = RANDOM.nextInt(RANDOM_RANGE);
  561.                 }
  562.                 Thread.sleep(r);
  563.             } catch (Exception e) {
  564.                 //do nothing
  565.             }
  566.             synchronized (this) {
  567.                 if (numCuttings <= 0) {
  568.                     PointsException e = new PointsException(5, "Brojot na klienti koi se strizat e 0 i nema koj da izleze.");
  569.                     log(e, null);
  570.                 }
  571.                 numCuttings--;
  572.             }
  573.  
  574.         }
  575.  
  576.         public synchronized void customerPay() throws RuntimeException {
  577.             log(null, "customer is paying and leaving the shop");
  578.  
  579.  
  580.         }
  581.  
  582.         public synchronized void barberGoToSleep() throws RuntimeException {
  583.             Barber b = (Barber) Thread.currentThread();
  584.             if (!barberWaked[b.barberId]) {
  585.                 PointsException e = new PointsException(5, "Berberite veke spijat i ne moze da se prezaspijat.");
  586.                 log(e, null);
  587.             }
  588.             if (arrivedCustomers > 0) {
  589.                 PointsException e = new PointsException(5, "Seuste ima klienti koi cekaat i berberot ne moze da odi na spienje.");
  590.                 log(e, null);
  591.             }
  592.             log(null, "all barbers go to sleap");
  593.             barberWaked[b.barberId] = false;
  594.         }
  595.         private List<String> actions = new ArrayList<String>();
  596.         private List<PointsException> exceptions = new ArrayList<PointsException>();
  597.  
  598.         private synchronized void log(PointsException e, String action) {
  599.             TemplateThread t = (TemplateThread) Thread.currentThread();
  600.             if (e == null) {
  601.                 actions.add(t.toString() + "\t(a): " + action);
  602.             } else {
  603.                 t.setException(e);
  604.                 actions.add(t.toString() + "\t(e): " + e.getMessage());
  605.             }
  606.         }
  607.  
  608.         public synchronized void printLog() {
  609.             System.out.println("Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
  610.             System.out.println("Log na izvrsuvanje na akciite:");
  611.             System.out.println("=========================");
  612.             System.out.println("tip\tid\titer\takcija/error");
  613.             System.out.println("=========================");
  614.             for (String l : actions) {
  615.                 System.out.println(l);
  616.             }
  617.         }
  618.  
  619.         public void printStatus() {
  620.             if (!TemplateThread.hasException) {
  621.                 int poeni = 25;
  622.                 if (PointsException.getTotalPoints() == 0) {
  623.                     System.out.println("Procesot e uspesno sinhroniziran. Osvoeni 25 poeni.");
  624.                 } else {
  625.                     poeni -= PointsException.getTotalPoints();
  626.                     PointsException.printErrors();
  627.                     System.out.println("Osvoeni poeni: " + poeni);
  628.                 }
  629.  
  630.             } else {
  631.                 System.out.println("Procesot ne e sinhroniziran spored uslovite na zadacata");
  632.                 printLog();
  633.                 System.out.println("====================================================");
  634.                 PointsException.printErrors();
  635.                 System.out.println("Maksimum Poeni: " + (25 - PointsException.getTotalPoints()));
  636.             }
  637.  
  638.         }
  639.     }
  640.  
  641.     abstract static class TemplateThread extends Thread {
  642.  
  643.         static boolean hasException = false;
  644.         int numRuns = 1;
  645.         public int iteration = 0;
  646.         private Exception exception = null;
  647.  
  648.         public TemplateThread(int numRuns) {
  649.             this.numRuns = numRuns;
  650.         }
  651.  
  652.         abstract void execute() throws InterruptedException;
  653.  
  654.         @Override
  655.         public void run() {
  656.             try {
  657.                 for (int i = 0; i < numRuns && !hasException; i++) {
  658.                     execute();
  659.                     iteration++;
  660.  
  661.                 }
  662.             } catch (InterruptedException e) {
  663.                 // Do nothing
  664.             } catch (Exception e) {
  665.                 exception = e;
  666.                 hasException = true;
  667.             }
  668.         }
  669.  
  670.         public void setException(Exception exception) {
  671.             this.exception = exception;
  672.             hasException = true;
  673.         }
  674.  
  675.         @Override
  676.         public String toString() {
  677.             Thread current = Thread.currentThread();
  678.             if (numRuns > 1) {
  679.                 return String.format("%s\t%d\t%d", "" + current.getClass().getSimpleName().charAt(0), getId(), iteration);
  680.             } else {
  681.                 return String.format("%s\t%d\t", "" + current.getClass().getSimpleName().charAt(0), getId());
  682.             }
  683.         }
  684.     }
  685.  
  686.     static class PointsException extends RuntimeException {
  687.  
  688.         private static HashMap<String, PointsException> exceptions = new HashMap<String, PointsException>();
  689.         private int points;
  690.  
  691.         public PointsException(int points, String message) {
  692.             super(message);
  693.             this.points = points;
  694.             exceptions.put(message, this);
  695.         }
  696.  
  697.         public static int getTotalPoints() {
  698.             int sum = 0;
  699.             for (PointsException e : exceptions.values()) {
  700.                 sum += e.getPoints();
  701.             }
  702.             return sum;
  703.         }
  704.  
  705.         public static void printErrors() {
  706.             System.out.println("Gi imate slednite greski: ");
  707.             for (Map.Entry<String, PointsException> e : exceptions.entrySet()) {
  708.                 System.out.println(String.format("[%s] : (-%d)", e.getKey(), e.getValue().getPoints()));
  709.             }
  710.         }
  711.  
  712.         public int getPoints() {
  713.             return points;
  714.         }
  715.     }
  716.  
  717.     public static void main(String[] args) {
  718.         try {
  719.             start();
  720.         } catch (Exception ex) {
  721.             ex.printStackTrace();
  722.         }
  723.     }
  724.  
  725.     public static void start() throws Exception {
  726.         Scanner s = new Scanner(System.in);
  727.         int brBarbers = s.nextInt();
  728.         int brKonzumeri = s.nextInt();
  729.         int numBarberRuns = s.nextInt();
  730.         int numCustomerRuns = s.nextInt();
  731.         init(brBarbers);
  732.  
  733.         state = new State(brBarbers);
  734.         HashSet<Thread> threads = new HashSet<Thread>();
  735.  
  736.         for (int i = 0; i < brBarbers; i++) {
  737.             Barber prod = new Barber(numBarberRuns, i);
  738.             threads.add(prod);
  739.             prod.start();
  740.             Consumer c = new Consumer(numCustomerRuns);
  741.             threads.add(c);
  742.             c.start();
  743.         }
  744.  
  745.         for (int i = 0; i < brKonzumeri / 2 - brBarbers; i++) {
  746.             Consumer c = new Consumer(numCustomerRuns);
  747.             threads.add(c);
  748.             c.start();
  749.         }
  750.         try {
  751.             Thread.sleep(50);
  752.         } catch (Exception e) {
  753.             //do nothing
  754.         }
  755.         for (int i = 0; i < brKonzumeri / 2; i++) {
  756.             Consumer c = new Consumer(numCustomerRuns);
  757.             threads.add(c);
  758.             c.start();
  759.         }
  760.  
  761.  
  762.         for (Thread t : threads) {
  763.             t.join(1000);
  764.         }
  765.  
  766.         for (Thread t : threads) {
  767.             if (t.isAlive()) {
  768.                 t.interrupt();
  769.             }
  770.         }
  771.  
  772.         state.printStatus();
  773.     }
  774.     //</editor-fold>
  775. }
  776.  
  777.  
  778.  
  779.  
  780.  
  781. /*
  782. Task 3 Problem 1 (1 / 1)
  783. A tribe is eating a dinner prepared in a large kettle which holds a limited number of portions. Each tribe member takes a portion on his own, if there is food in the kettle. If the kettle is empty, the cooking chef is called to prepare a new kettle full of food. Only one tribe member can check if the kettle is empty at a given moment. However, there are three places around the kettle, meaning three tribe members can take food in parallel. The number of member eating concurrently is not limited.
  784.  
  785. The kettle is empty initially.
  786.  
  787. Your task is to synchronize the given scenario.
  788.  
  789. In the starter code, you have a definition of the TribeMember class, which represents the tribe members and their behavior. There are multiple instances of TribeMember in which the execute() method is called multiple times.
  790.  
  791. In your implementation you can use the following methods from state:
  792.  
  793. state.isPotEmpty()
  794. Used to check if there is still food in the kettle. It manipulates with a global variable and should be treated as a critical region.
  795. If more than one tribe member checks at the same time, the call will throw an exception.
  796. state.fillPlate()
  797. Represents taking food from the kettle.
  798. If the kettle is empty, or more then 3 tribe member all it in parallel, it will throw an exception
  799. state.eat()
  800. Represents the consuming of food by the tribe member.
  801. state.cook()
  802. Represents the cooking done by the cooking chef.
  803. If the kettle is not empty, it will throw an exception.
  804. These methods are used for validation the scenario and cannot be changed. They need to be called.
  805.  
  806. Your task is to implement the methods TribeMember.execute() and init(). In your implementation, you can not add try-catch blocks in them. You should define the necessary semaphores and other variables.
  807.  
  808. If you have an error, you will get this message:
  809.  
  810. Procesot ne e sinhroniziran spored uslovite na zadacata // The process in not synchronized according to the conditions in the task
  811.  
  812. After that you will see the log of actions and errors. Use this log to see what went wrong,
  813.  
  814. Note: Due to concurrent execution of the logging, it is possible that some of the messages in the log are not in the position they are supposed to be. Therefore, use them only as guideline information, do not base all of the conclusions on them.
  815. */
  816.  
  817. import java.util.ArrayList;
  818. import java.util.HashMap;
  819. import java.util.HashSet;
  820. import java.util.List;
  821. import java.util.Map;
  822. import java.util.Random;
  823. import java.util.Scanner;
  824. import java.util.concurrent.Semaphore;
  825. import java.util.concurrent.atomic.AtomicInteger;
  826.  
  827. public class TribeDinner {
  828.  
  829.     // TODO: definirajte gi semaforite i ostanatite promenlivi ovde (mora site da se static)
  830.     private static Semaphore kettleAccess;
  831.     private static Object checkKettle;
  832.  
  833.     /**
  834.      * Metod koj treba da gi inicijalizira vrednostite na semaforite i
  835.      * ostanatite promenlivi za sinhronizacija.
  836.      *
  837.      *
  838.      * TODO: da se implementira
  839.      *
  840.      */
  841.     public static void init(int numBarbers) {
  842.         kettleAccess = new Semaphore(3);
  843.         checkKettle = new Object();
  844.     }
  845.  
  846.     static class TribeMember extends TemplateThread {
  847.  
  848.         public TribeMember(int numRuns) {
  849.             super(numRuns);
  850.         }
  851.  
  852.         /**
  853.          * Da se implementira odnesuvanjeto na ucesnikot spored uslovite na
  854.          * zadacata.
  855.          */
  856.         public void execute() throws InterruptedException {
  857.             kettleAccess.acquire();
  858.             synchronized(checkKettle) {
  859.                 if(state.isPotEmpty()) {
  860.                     state.cook();
  861.                 }
  862.             }
  863.             state.fillPlate(); // 3 can fill plates
  864.             kettleAccess.release();
  865.  
  866.             state.eat(); // not limited
  867.         }
  868.     }
  869.  
  870.     // <editor-fold defaultstate="collapsed" desc="This is the template code" >
  871.     static State state;
  872.  
  873.     static class State {
  874.  
  875.         private static final String _10_JADENJETO_NE_E_PARALELIZIRANO = "jadenjeto ne e paralelizirano. Site jadat eden po eden";
  876.         private static final String _10_PRISTAPOT_DO_KAZANOT_NE_E_PARALELIZIRAN = "Pristapot do kazanot ne e paraleliziran. Treda da moze do trojca paralelno da zemaat hrana.";
  877.  
  878.         private static final String _10_DVAJCA_ISTOVREMENO_PROVERUVAAT = "Dvajca istovremeno proveruvaat dali kazanot e prazen. Maksimum eden e dozvoleno.";
  879.         private static final String _7_NEMA_MESTO_POKRAJ_KAZANOT = "Nema mesto pokraj kazanot. Maksimum tri clena moze da zemaat hrana istovremeno.";
  880.         private static final String _5_NE_MOZE_DA_JADE_OD_PRAZEN_KAZAN = "Ne moze da jade od prazen kazan. Treba da se povika 'state.cook()'";
  881.         private static final String _5_NE_MOZE_DA_SE_GOTVI_VO_KAZAN_KOJ_NE_E_PRAZEN = "Ne moze da se gotvi vo kazan koj ne e prazen";
  882.  
  883.         private static final Random RANDOM = new Random();
  884.         private static final int POT_CAPACITY = 15;
  885.  
  886.         private LimitedCounter platesLeft = new LimitedCounter(0, null, 0,
  887.                 null, 0, 5, _5_NE_MOZE_DA_JADE_OD_PRAZEN_KAZAN);
  888.  
  889.         private LimitedCounter checks = new LimitedCounter(0, 1, 10,
  890.                 _10_DVAJCA_ISTOVREMENO_PROVERUVAAT, null, 0, null);
  891.  
  892.         private LimitedCounter fills = new LimitedCounter(0, 3, 7,
  893.                 _7_NEMA_MESTO_POKRAJ_KAZANOT, null, 0, null);
  894.  
  895.         private LimitedCounter eat = new LimitedCounter(0);
  896.  
  897.         public State() {
  898.  
  899.         }
  900.  
  901.         public boolean isPotEmpty() throws RuntimeException {
  902.             log(checks.incrementWithMax(), "proverka dali ima hrana vo kazanot");
  903.             sleep(5);
  904.             boolean res = platesLeft.getValue() == 0;
  905.             log(checks.decrementWithMin(), null);
  906.             return res;
  907.         }
  908.  
  909.         public void fillPlate() throws RuntimeException {
  910.             log(fills.incrementWithMax(), "zemanje na hrana");
  911.             log(platesLeft.decrementWithMin(), null);
  912.             sleep(5);
  913.             log(platesLeft.incrementWithMax(), null);
  914.             log(fills.decrementWithMin(), null);
  915.         }
  916.  
  917.         public void eat() throws RuntimeException {
  918.             log(eat.incrementWithMax(), "jadenje");
  919.             sleep(10);
  920.             log(eat.decrementWithMin(), null);
  921.         }
  922.  
  923.         public void cook() throws RuntimeException {
  924.             synchronized (State.class) {
  925.                 if (platesLeft.getValue() == 0) {
  926.                     platesLeft.setValue(POT_CAPACITY);
  927.                 } else {
  928.                     PointsException e = new PointsException(5,
  929.                             _5_NE_MOZE_DA_SE_GOTVI_VO_KAZAN_KOJ_NE_E_PRAZEN);
  930.                     log(e, null);
  931.                 }
  932.             }
  933.         }
  934.  
  935.         public void finalize() {
  936.             if (fills.getMax() == 1) {
  937.                 logException(new PointsException(10,
  938.                         _10_PRISTAPOT_DO_KAZANOT_NE_E_PARALELIZIRAN));
  939.             }
  940.             if (eat.getMax() == 1) {
  941.                 logException(new PointsException(10,
  942.                         _10_JADENJETO_NE_E_PARALELIZIRANO));
  943.             }
  944.         }
  945.  
  946.         private List<String> actions = new ArrayList<String>();
  947.  
  948.         private void sleep(int range) {
  949.             try {
  950.                 Thread.sleep(RANDOM.nextInt(range));
  951.             } catch (InterruptedException e) {
  952.             }
  953.         }
  954.  
  955.         protected TemplateThread getThread() {
  956.             TemplateThread t = (TemplateThread) Thread.currentThread();
  957.             return t;
  958.         }
  959.  
  960.         private synchronized void log(PointsException e, String action) {
  961.             TemplateThread t = (TemplateThread) Thread.currentThread();
  962.             if (e != null) {
  963.                 t.setException(e);
  964.                 actions.add(t.toString() + "\t(e): " + e.getMessage());
  965.             } else if (action != null) {
  966.                 actions.add(t.toString() + "\t(a): " + action);
  967.             }
  968.         }
  969.  
  970.         private synchronized void logException(PointsException e) {
  971.             actions.add("\t(e): " + e.getMessage());
  972.         }
  973.  
  974.         public synchronized void printLog() {
  975.             System.out
  976.                     .println("Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
  977.             System.out.println("Log na izvrsuvanje na akciite:");
  978.             System.out.println("=========================");
  979.             System.out.println("tip\tid\titer\takcija/error");
  980.             System.out.println("=========================");
  981.             for (String l : actions) {
  982.                 System.out.println(l);
  983.             }
  984.         }
  985.  
  986.         public void printStatus() {
  987.             finalize();
  988.             if (!TemplateThread.hasException) {
  989.                 int poeni = 25;
  990.                 if (PointsException.getTotalPoints() == 0) {
  991.                     System.out
  992.                             .println("Procesot e uspesno sinhroniziran. Osvoeni 25 poeni.");
  993.                 } else {
  994.                     poeni -= PointsException.getTotalPoints();
  995.                     PointsException.printErrors();
  996.                     System.out.println("Maksimalni osvoeni poeni: " + poeni);
  997.                 }
  998.  
  999.             } else {
  1000.                 System.out
  1001.                         .println("Procesot ne e sinhroniziran spored uslovite na zadacata");
  1002.                 printLog();
  1003.                 System.out
  1004.                         .println("====================================================");
  1005.                 PointsException.printErrors();
  1006.                 int total = (25 - PointsException.getTotalPoints());
  1007.                 if (total < 0) {
  1008.                     total = 0;
  1009.                 }
  1010.                 System.out.println("Maksimum Poeni: " + total);
  1011.             }
  1012.  
  1013.         }
  1014.     }
  1015.  
  1016.     static class LimitedCounter {
  1017.  
  1018.         private int value;
  1019.         private Integer maxAllowed;
  1020.         private Integer minAllowed;
  1021.         private int maxErrorPoints;
  1022.         private int minErrorPoints;
  1023.         private String maxErrorMessage;
  1024.         private String minErrorMessage;
  1025.  
  1026.         private int max;
  1027.  
  1028.         public LimitedCounter(int value) {
  1029.             super();
  1030.             this.value = value;
  1031.             this.max = value;
  1032.         }
  1033.  
  1034.         public LimitedCounter(int value, Integer maxAllowed,
  1035.                               int maxErrorPoints, String maxErrorMessage, Integer minAllowed,
  1036.                               int minErrorPoints, String minErrorMessage) {
  1037.             super();
  1038.             this.value = value;
  1039.             this.max = value;
  1040.             this.maxAllowed = maxAllowed;
  1041.             this.minAllowed = minAllowed;
  1042.             this.maxErrorPoints = maxErrorPoints;
  1043.             this.minErrorPoints = minErrorPoints;
  1044.             this.maxErrorMessage = maxErrorMessage;
  1045.             this.minErrorMessage = minErrorMessage;
  1046.         }
  1047.  
  1048.         public int getMax() {
  1049.             return max;
  1050.         }
  1051.  
  1052.         public int getValue() {
  1053.             return value;
  1054.         }
  1055.  
  1056.         public void setValue(int value) {
  1057.             this.value = value;
  1058.         }
  1059.  
  1060.         public PointsException incrementWithMax() {
  1061.             synchronized (LimitedCounter.class) {
  1062.                 value++;
  1063.                 if (value > max) {
  1064.                     max = value;
  1065.                 }
  1066.                 if (maxAllowed != null) {
  1067.                     if (value > maxAllowed) {
  1068.                         PointsException e = new PointsException(maxErrorPoints,
  1069.                                 maxErrorMessage);
  1070.                         return e;
  1071.                     }
  1072.                 }
  1073.             }
  1074.             return null;
  1075.         }
  1076.  
  1077.         public PointsException decrementWithMin() {
  1078.             synchronized (LimitedCounter.class) {
  1079.                 value--;
  1080.                 if (minAllowed != null) {
  1081.                     if (value < minAllowed) {
  1082.                         PointsException e = new PointsException(minErrorPoints,
  1083.                                 minErrorMessage);
  1084.                         return e;
  1085.                     }
  1086.                 }
  1087.             }
  1088.             return null;
  1089.         }
  1090.     }
  1091.  
  1092.     abstract static class TemplateThread extends Thread {
  1093.  
  1094.         static boolean hasException = false;
  1095.         int numRuns = 1;
  1096.         public int iteration = 0;
  1097.         protected Exception exception = null;
  1098.  
  1099.         public TemplateThread(int numRuns) {
  1100.             this.numRuns = numRuns;
  1101.         }
  1102.  
  1103.         abstract void execute() throws InterruptedException;
  1104.  
  1105.         @Override
  1106.         public void run() {
  1107.             try {
  1108.                 for (int i = 0; i < numRuns && !hasException; i++) {
  1109.                     execute();
  1110.                     iteration++;
  1111.  
  1112.                 }
  1113.             } catch (InterruptedException e) {
  1114.                 // Do nothing
  1115.             } catch (Exception e) {
  1116.                 exception = e;
  1117.                 hasException = true;
  1118.             }
  1119.         }
  1120.  
  1121.         public void setException(Exception exception) {
  1122.             this.exception = exception;
  1123.             hasException = true;
  1124.         }
  1125.  
  1126.         @Override
  1127.         public String toString() {
  1128.             Thread current = Thread.currentThread();
  1129.             if (numRuns > 1) {
  1130.                 return String.format("%s\t%d\t%d", ""
  1131.                                 + current.getClass().getSimpleName().charAt(0),
  1132.                         getId(), iteration);
  1133.             } else {
  1134.                 return String
  1135.                         .format("%s\t%d\t", ""
  1136.                                         + current.getClass().getSimpleName().charAt(0),
  1137.                                 getId());
  1138.             }
  1139.         }
  1140.     }
  1141.  
  1142.     static class PointsException extends RuntimeException {
  1143.  
  1144.         private static HashMap<String, PointsException> exceptions = new HashMap<String, PointsException>();
  1145.         private int points;
  1146.  
  1147.         public PointsException(int points, String message) {
  1148.             super(message);
  1149.             this.points = points;
  1150.             exceptions.put(message, this);
  1151.         }
  1152.  
  1153.         public static int getTotalPoints() {
  1154.             int sum = 0;
  1155.             for (PointsException e : exceptions.values()) {
  1156.                 sum += e.getPoints();
  1157.             }
  1158.             return sum;
  1159.         }
  1160.  
  1161.         public static void printErrors() {
  1162.             System.out.println("Gi imate slednite greski: ");
  1163.             for (Map.Entry<String, PointsException> e : exceptions.entrySet()) {
  1164.                 System.out.println(String.format("[%s] : (-%d)", e.getKey(), e
  1165.                         .getValue().getPoints()));
  1166.             }
  1167.         }
  1168.  
  1169.         public int getPoints() {
  1170.             return points;
  1171.         }
  1172.     }
  1173.  
  1174.     public static void main(String[] args) {
  1175.         try {
  1176.             start();
  1177.         } catch (Exception ex) {
  1178.             ex.printStackTrace();
  1179.         }
  1180.     }
  1181.  
  1182.     public static void start() throws Exception {
  1183.         Scanner s = new Scanner(System.in);
  1184.         int brKonzumeri = s.nextInt();
  1185.         int numCustomerRuns = s.nextInt();
  1186.         init(brKonzumeri);
  1187.  
  1188.         state = new State();
  1189.         HashSet<Thread> threads = new HashSet<Thread>();
  1190.  
  1191.         for (int i = 0; i < brKonzumeri; i++) {
  1192.             TribeMember c = new TribeMember(numCustomerRuns);
  1193.             threads.add(c);
  1194.             c.start();
  1195.         }
  1196.         try {
  1197.             Thread.sleep(50);
  1198.         } catch (Exception e) {
  1199.             // do nothing
  1200.         }
  1201.  
  1202.         for (Thread t : threads) {
  1203.             t.join(1000);
  1204.         }
  1205.  
  1206.         for (Thread t : threads) {
  1207.             if (t.isAlive()) {
  1208.                 t.interrupt();
  1209.                 if (t instanceof TemplateThread) {
  1210.                     TemplateThread tt = (TemplateThread) t;
  1211.                     tt.setException(new PointsException(25, "DEADLOCK"));
  1212.                 }
  1213.             }
  1214.         }
  1215.         s.close();
  1216.         state.printStatus();
  1217.     }
  1218.     // </editor-fold>
  1219. }
  1220.  
  1221.  
  1222.  
  1223.  
  1224.  
  1225.  
  1226. /*
  1227. Task 4 Problem 1 (1 / 1)
  1228. Implement a mini voting system. In the beginning, all the candidates are saved at the server side, along with their respective numbers (ex. Petar Kostandinov - 1, Ilija Petkovski - 2 etc). The client, after connecting to the server, should receive the entire voting list and choose the desired candidate, by sending the candidate number to the server. Any client can, at any time, get the results for each candidate. The server allows maximum 100 clients connected at the same moment.
  1229.  
  1230. Note: Define the communication protocol - define the set of states and the format of the messages that are to be sent.
  1231. */
  1232.  
  1233. import java.io.*;
  1234. import java.net.ServerSocket;
  1235. import java.net.Socket;
  1236. import java.util.HashMap;
  1237. import java.util.HashSet;
  1238. import java.util.Scanner;
  1239. import java.util.concurrent.Semaphore;
  1240.  
  1241. public class TCPVotingSystemServer {
  1242.     ServerSocket server;
  1243.     HashMap<Integer, Candidate> candidates;
  1244.     HashMap<Integer, Socket> connections;
  1245.     Semaphore maxClients;
  1246.  
  1247.     public static final String ANSI_GREEN = "\u001B[32m";
  1248.     public static final String ANSI_YELLOW = "\u001B[33m";
  1249.     public static final String ANSI_BLUE = "\u001B[34m";
  1250.     public static final String ANSI_PURPLE = "\u001B[35m";
  1251.     public static final String ANSI_CYAN = "\u001B[36m";
  1252.     public static final String ANSI_WHITE = "\u001B[37m";
  1253.  
  1254.     public TCPVotingSystemServer(Integer port) {
  1255.         try {
  1256.             this.server = new ServerSocket(port);
  1257.             candidates = new HashMap<>();
  1258.             connections = new HashMap<>(1000);
  1259.             this.maxClients = new Semaphore(100);
  1260.         } catch (IOException e) {
  1261.             e.printStackTrace();
  1262.         }
  1263.     }
  1264.  
  1265.     public void addNewCandidate(int number, String name) {
  1266.         candidates.put(number, new Candidate(name, number));
  1267.     }
  1268.  
  1269.     public void addNewConnection(int id, Socket connection) {
  1270.         connections.put(id, connection);
  1271.     }
  1272.  
  1273.     public void removeConnection(int id) {
  1274.         connections.remove(id);
  1275.         maxClients.release();
  1276.     }
  1277.  
  1278.     public void listen() throws IOException, InterruptedException {
  1279.         while(true) {
  1280.             maxClients.acquire();
  1281.  
  1282.             // Accept incoming connection
  1283.             Socket newClient = server.accept();
  1284.  
  1285.             // Create input and output streams
  1286.             DataInputStream br = new DataInputStream(newClient.getInputStream());
  1287.             DataOutputStream bw = new DataOutputStream(newClient.getOutputStream());
  1288.  
  1289.             ServerWorkerThread newConnection = new ServerWorkerThread(this, newClient, br, bw);
  1290.             newConnection.start();
  1291.         }
  1292.     }
  1293.  
  1294.     public static void main(String[] args) {
  1295.         try {
  1296.             int noCandidates;
  1297.             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  1298.  
  1299.             TCPVotingSystemServer server = new TCPVotingSystemServer(9000);
  1300.             System.out.println(ANSI_GREEN + "Server successfully created (Port: 9000)");
  1301.             System.out.println(ANSI_BLUE + "---------------- ( SETUP ) ----------------");
  1302.             System.out.print("Insert number of candidates: ");
  1303.             noCandidates = Integer.parseInt(br.readLine());
  1304.             for (int i = 0; i < noCandidates; i++) {
  1305.                 System.out.print(ANSI_BLUE + "(Candidate: " + i+1 + ") Number: ");
  1306.                 int number = Integer.parseInt(br.readLine());
  1307.                 System.out.print(ANSI_BLUE + "(Candidate: " + i+1 + ") Name: ");
  1308.                 String name = br.readLine();
  1309.                 server.addNewCandidate(number, name);
  1310.             }
  1311.             System.out.println(ANSI_BLUE + "------------ ( SETUP FINISHED ) ------------");
  1312.  
  1313.             server.listen();
  1314.         } catch(Exception e) {
  1315.             System.err.println("ERROR: Something went wrong!");
  1316.         }
  1317.     }
  1318. }
  1319.  
  1320. class ServerWorkerThread extends Thread {
  1321.     TCPVotingSystemServer server;
  1322.     Socket client;
  1323.     DataInputStream in;
  1324.     DataOutputStream out;
  1325.     Integer connectionId;
  1326.  
  1327.     public static final String ANSI_GREEN = "\u001B[32m";
  1328.     public static final String ANSI_YELLOW = "\u001B[33m";
  1329.     public static final String ANSI_BLUE = "\u001B[34m";
  1330.     public static final String ANSI_PURPLE = "\u001B[35m";
  1331.     public static final String ANSI_CYAN = "\u001B[36m";
  1332.     public static final String ANSI_WHITE = "\u001B[37m";
  1333.  
  1334.     ServerWorkerThread(TCPVotingSystemServer server, Socket client, DataInputStream in, DataOutputStream out) {
  1335.         this.server = server;
  1336.         this.client = client;
  1337.         this.in = in;
  1338.         this.out = out;
  1339.         this.connectionId = null;
  1340.     }
  1341.  
  1342.     public void listen() throws IOException {
  1343.         while(true) {
  1344.             if(client.isClosed()) break;
  1345.             String recievedCommand;
  1346.             recievedCommand = in.readUTF().trim();
  1347.             if(recievedCommand.equals("CloseConnection")) {
  1348.                 out.writeUTF("(Client ID: " + connectionId + ") Connection successfully closed");
  1349.                 out.flush();
  1350.                 server.removeConnection(connectionId);
  1351.                 client.close();
  1352.                 continue;
  1353.             } else if(recievedCommand.contains("Vote")) {
  1354.                 String parts[] = recievedCommand.split("\\s");
  1355.                 Candidate c = server.candidates.get(Integer.parseInt(parts[1]));
  1356.                 if(c != null) {
  1357.                     c.addVote();
  1358.                     out.writeUTF("(Client ID: " + connectionId + ") Successfully voted!");
  1359.                     out.flush();
  1360.                 } else {
  1361.                     out.writeUTF("Invalid client id!");
  1362.                     out.flush();
  1363.                 }
  1364.             } else if(recievedCommand.contains("GetList")) {
  1365.                 StringBuilder sb = new StringBuilder();
  1366.                 sb.append("--------------- (VOTE LIST) ---------------\n");
  1367.                 for(Candidate c : server.candidates.values()) {
  1368.                     sb.append(c + "\n");
  1369.                 }
  1370.                 sb.append("--------------- (VOTE LIST) ---------------\n");
  1371.                 out.writeUTF(sb.toString());
  1372.                 out.flush();
  1373.             } else {
  1374.                 out.writeUTF("Invalid command");
  1375.                 out.flush();
  1376.             }
  1377.         }
  1378.     }
  1379.  
  1380.     @Override
  1381.     public void run() {
  1382.         try {
  1383.             this.connectionId = in.readInt();
  1384.             server.addNewConnection(connectionId, client);
  1385.  
  1386.             System.out.println(ANSI_PURPLE + "SERVER: " + ANSI_WHITE + "New client arrived (ID: " + connectionId + ")");
  1387.             listen();
  1388.         } catch (IOException e) {
  1389.             e.printStackTrace();
  1390.         }
  1391.     }
  1392. }
  1393.  
  1394. class Candidate {
  1395.     String name;
  1396.     int number;
  1397.     int votes;
  1398.  
  1399.     public Candidate(String name, int number) {
  1400.         this.name = name;
  1401.         this.number = number;
  1402.         this.votes = 0;
  1403.     }
  1404.  
  1405.     public void addVote() {
  1406.         votes++;
  1407.     }
  1408.  
  1409.     @Override
  1410.     public String toString() {
  1411.         return String.format("Candidate: %s (%d) | Votes: %d", name, number, votes);
  1412.     }
  1413. }
  1414.  
  1415.  
  1416.  
  1417. import java.io.*;
  1418. import java.net.InetAddress;
  1419. import java.net.Socket;
  1420. import java.util.HashSet;
  1421. import java.util.Random;
  1422.  
  1423. public class TCPVotingSystemClient {
  1424.  
  1425.     private static final String ANSI_GREEN = "\u001B[32m";
  1426.     private static final String ANSI_YELLOW = "\u001B[33m";
  1427.     private static final String ANSI_BLUE = "\u001B[34m";
  1428.     private static final String ANSI_PURPLE = "\u001B[35m";
  1429.     private static final String ANSI_CYAN = "\u001B[36m";
  1430.     private static final String ANSI_WHITE = "\u001B[37m";
  1431.  
  1432.     public static void main(String[] args) {
  1433.         try {
  1434.             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  1435.             HashSet<ClientWorkerThread> clients = new HashSet<>(1000);
  1436.  
  1437.             for(int i=0; i<1000; i++) {
  1438.                 clients.add(new ClientWorkerThread(i, false));
  1439.             }
  1440.  
  1441.             clients.forEach(Thread::start);
  1442.  
  1443.             new ClientWorkerThread(0, true).start();
  1444.         } catch(Exception e) {
  1445.             e.printStackTrace();
  1446.             System.err.println("ERROR: Something went wrong!");
  1447.         }
  1448.     }
  1449. }
  1450.  
  1451. class ClientWorkerThread extends Thread {
  1452.     private Socket connection;
  1453.     private DataInputStream in;
  1454.     private DataOutputStream out;
  1455.     private Integer id;
  1456.  
  1457.     private static final String ANSI_GREEN = "\u001B[32m";
  1458.     private static final String ANSI_YELLOW = "\u001B[33m";
  1459.     private static final String ANSI_BLUE = "\u001B[34m";
  1460.     private static final String ANSI_PURPLE = "\u001B[35m";
  1461.     private static final String ANSI_CYAN = "\u001B[36m";
  1462.     private static final String ANSI_WHITE = "\u001B[37m";
  1463.  
  1464.     public ClientWorkerThread(int id, boolean test) {
  1465.         if(test == true) this.id = 1212121;
  1466.         else this.id = id;
  1467.     }
  1468.  
  1469.     private void sendClientID(int id) throws IOException {
  1470.         out.writeInt(id);
  1471.         out.flush();
  1472.     }
  1473.  
  1474.     public void sendCommand(String command) throws IOException {
  1475.         try {
  1476.             out.writeUTF(command);
  1477.             out.flush();
  1478.             System.out.println(ANSI_YELLOW + in.readUTF());
  1479.         } catch (IOException e) {
  1480.             e.printStackTrace();
  1481.         }
  1482.     }
  1483.  
  1484.     @Override
  1485.     public synchronized void start() {
  1486.         try {
  1487.             this.connection = new Socket(InetAddress.getByName("localhost"), 9000);
  1488.             this.in = new DataInputStream(connection.getInputStream());
  1489.             this.out = new DataOutputStream(connection.getOutputStream());
  1490.  
  1491.             sendClientID(id);
  1492.  
  1493.             Random r = new Random();
  1494.             sendCommand("Vote " + (r.nextInt(2)+1));
  1495.             if(this.id == 1212121) sendCommand("GetList");
  1496.             sendCommand("CloseConnection");
  1497.         } catch (IOException e) {
  1498.             e.printStackTrace();
  1499.         }
  1500. //        System.out.println(ANSI_BLUE + "---------------- ( Available commands ) ----------------");
  1501. //        System.out.println(ANSI_PURPLE + "GetList " + ANSI_BLUE + "// get the list with the candidates and their current votes.");
  1502. //        System.out.println(ANSI_PURPLE + "Vote number " + ANSI_BLUE + "// Vote for some candidate.");
  1503. //        System.out.println(ANSI_PURPLE + "CloseConnection " + ANSI_BLUE + "// Closes the connection.");
  1504. //        System.out.println(ANSI_BLUE + "Type the commands in the following format ClientID: Command ");
  1505. //        System.out.println(ANSI_BLUE + "Example:" + ANSI_CYAN + " 1: GetList");
  1506. //        System.out.println(ANSI_BLUE + "---------------- ( Available commands ) ----------------");
  1507.     }
  1508. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement