Advertisement
Guest User

Untitled

a guest
Oct 28th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.20 KB | None | 0 0
  1. package server;
  2.  
  3. import java.net.*;
  4. import java.rmi.Naming;
  5. import java.rmi.NotBoundException;
  6. import java.rmi.RemoteException;
  7. import java.rmi.registry.LocateRegistry;
  8. import java.rmi.server.UnicastRemoteObject;
  9. import java.util.ArrayList;
  10. import java.util.HashMap;
  11. import java.util.InputMismatchException;
  12. import java.util.Scanner;
  13. import java.util.StringTokenizer;
  14. import java.io.*;
  15. import static java.lang.System.*;
  16.  
  17. public class TCPServer {
  18.  
  19. public static String rmiHost;
  20. public static int rmiPort;
  21. public static int rmiPortBackUp;
  22. public static String ServerAHost;
  23. public static int ServerAPort;
  24. public static String ServerBHost;
  25. public static int ServerBPort;
  26. public static RMI rmiMain;
  27.  
  28. public static void main(String[] args) throws RemoteException {
  29. carregaServerConfig();
  30. // ServerA servidor = new ServerA(serverAHost,serverAPort,rmiHost,rmiPort);
  31. Scanner sc1 = new Scanner(System.in);
  32. System.out.print("1 - ServerA\n2 - ServerB\n: ");
  33. String opc = sc1.nextLine();
  34. final ArrayList<Connection> connections = new ArrayList<Connection>();
  35. Server server;//TODO interface para registar mesas
  36. try {
  37. rmiMain=(RMI) Naming.lookup("rmi://" + rmiHost + ":" + rmiPort + "/rmi");
  38. } catch (MalformedURLException e) {
  39. e.printStackTrace();
  40. } catch (RemoteException e) {
  41. e.printStackTrace();
  42. } catch (NotBoundException e) {
  43. e.printStackTrace();
  44. System.exit(0);
  45. }
  46. if (opc.equals("1")) {
  47. server=new Server(ServerAHost, ServerAPort, rmiHost, rmiPort,connections);
  48. } else {
  49. server=new Server(ServerBHost, ServerBPort, rmiHost, rmiPort,connections);
  50. }
  51. try {
  52. rmiMain.subscribe((Server_rmi)server);
  53. } catch (RemoteException e) {
  54. e.printStackTrace();
  55. }
  56. server.mesaVoto();
  57.  
  58. }
  59.  
  60.  
  61. public static void carregaServerConfig() {
  62. String file = "TCPServerConfig.txt";
  63. String line;
  64. StringTokenizer tokenizer;
  65. System.out.println("Uploding Server configurations...");
  66. try {
  67. FileReader inputFile = new FileReader(file);
  68. BufferedReader buffer = new BufferedReader(inputFile);
  69. for (int i = 0; i < 7; i++) {
  70. line = buffer.readLine();
  71. tokenizer = new StringTokenizer(line, "=");
  72. line = tokenizer.nextToken();
  73. if (line.equals("Server A Host")) {
  74. ServerAHost = tokenizer.nextToken();
  75. } else if (line.equals("Server A Port")) {
  76. ServerAPort = Integer.parseInt(tokenizer.nextToken());
  77. } else if (line.equals("RMI Host")) {
  78. rmiHost = tokenizer.nextToken();
  79. } else if (line.equals("RMI Port")) {
  80. rmiPort = Integer.parseInt(tokenizer.nextToken());
  81. } else if (line.equals("RMI PortBackUp")) {
  82. rmiPortBackUp = Integer.parseInt(tokenizer.nextToken());
  83. } else if (line.equals("Server B Host")) {
  84. ServerBHost = tokenizer.nextToken();
  85. } else if (line.equals("Server B Port")) {
  86. ServerBPort = Integer.parseInt(tokenizer.nextToken());
  87. }
  88. }
  89. buffer.close();
  90. } catch (FileNotFoundException e) {
  91. System.out.println("File " + file + " not found");
  92. System.exit(0);
  93. } catch (IOException e) {
  94. } catch (NullPointerException e) {
  95. System.out.println("Error updating the data from the files.");
  96. }
  97.  
  98. }
  99. }
  100.  
  101. class Server extends UnicastRemoteObject implements Server_rmi{
  102. /**
  103. *
  104. */
  105. private static final long serialVersionUID = 1L;
  106. public String myHost;
  107. public int myPort;
  108. public String rmiHost;
  109. public int rmiPort;
  110. public Receiver receiver;
  111. public RMI rmi = null;
  112. ArrayList<Connection> connections;
  113. ArrayList<Connection> connectionsDeleteCache;
  114. Mesas mesaVoto;
  115. ArrayList<String> buffer;
  116.  
  117. public Server(String myHost, int myPort, String rmiHost, int rmiPort,ArrayList<Connection> connections)throws RemoteException {
  118. this.myHost = myHost;
  119. this.myPort = myPort;
  120. this.rmiHost = rmiHost;
  121. this.rmiPort = rmiPort;
  122. this.connections=connections;
  123. buffer=new ArrayList<String>();
  124. this.connectionsDeleteCache= new ArrayList<Connection>();
  125.  
  126. try {
  127. rmi=(RMI) Naming.lookup("rmi://" + rmiHost + ":" + rmiPort + "/rmi");
  128. } catch (MalformedURLException e) {
  129. e.printStackTrace();
  130. } catch (RemoteException e) {
  131. e.printStackTrace();
  132. } catch (NotBoundException e) {
  133. e.printStackTrace();
  134. System.exit(0);
  135. }
  136. }
  137.  
  138. public void mesaVoto() {
  139.  
  140. String number_cc_string="";
  141. Scanner inputS = new Scanner(System.in);
  142. boolean mesa=false;
  143. ArrayList<Mesas> mesasVoto;
  144. int option=0;
  145. try {
  146.  
  147. while(mesa==false) {
  148. try {
  149. out.println("Choose the representative table!");
  150. mesasVoto=rmi.getMesasVoto();
  151. for(Mesas x:mesasVoto) {
  152. System.out.println(++option+" - "+x.toString());
  153. }
  154. try {
  155. if(mesasVoto.size()!=0) {
  156. option=testOption(0, mesasVoto.size());
  157. mesaVoto=mesasVoto.get(option-1);
  158. }else {
  159. out.println("Não existem mesas criadas!");
  160. System.exit(0);
  161. }
  162. }catch(IndexOutOfBoundsException e) {
  163. System.out.println("indexoutofboundsexception");
  164. }
  165. receiver = new Receiver(myPort, rmiHost, rmiPort,connections,mesaVoto,rmi);
  166. mesa=true;
  167. } catch (RemoteException e) {
  168. int check=0;
  169. while(check==0) {
  170. try {
  171. rmi=(RMI) Naming.lookup("rmi://" + rmiHost + ":" + rmiPort + "/rmi");
  172. check=1;
  173. } catch (NotBoundException e1) {
  174. check=0;
  175. e1.printStackTrace();
  176. }
  177. }
  178.  
  179. e.printStackTrace();
  180. }
  181. }
  182. while (true) {
  183. do {
  184. out.print("ID:");
  185. try {
  186. number_cc_string = inputS.nextLine();
  187. } catch (InputMismatchException e) {
  188. out.println("Invalid option");
  189. inputS.next();
  190. }
  191. } while (!checkNumbers(number_cc_string) || number_cc_string.length() != 8);
  192. addBuffer(number_cc_string);
  193. try {
  194. for(String pedido:buffer) {
  195. if(rmi.getATerminal(Integer.parseInt(pedido))) {
  196. out.println("ID aceite!");
  197. for(Connection x:connections) {
  198. if(x.isLive()) {
  199. if(x.available==true) {
  200. out.println("Terminal "+x.thread_id+" is free.");
  201. out.println("Go to terminal "+x.thread_id);
  202. x.outStream.println("Terminal unblocked of CC: "+pedido+"\n Press enter to continue your request.");
  203. x.cc=pedido;
  204. x.available=false;
  205. break;
  206. }else {
  207. out.println("Terminal "+x.thread_id+" occupied.");
  208. }
  209. }else {
  210. connectionsDeleteCache.add(x);
  211. }
  212. }
  213. for(Connection x:connectionsDeleteCache) {
  214. connections.remove(x);
  215. }
  216. connectionsDeleteCache.clear();
  217. }else {
  218. out.println("Your cc does not exist");
  219. }
  220. }
  221. buffer.clear();
  222. }catch(RemoteException e) {
  223. int check=0;
  224. while(check==0) {
  225. do {
  226. out.print("ID:");
  227. try {
  228. number_cc_string = inputS.nextLine();
  229. } catch (InputMismatchException e1) {
  230. out.println("Invalid option");
  231. inputS.next();
  232. }
  233. } while (!checkNumbers(number_cc_string) || number_cc_string.length() != 8);
  234. addBuffer(number_cc_string);
  235. try {
  236. rmi=(RMI) Naming.lookup("rmi://" + rmiHost + ":" + rmiPort + "/rmi");
  237. for(String pedido:buffer) {
  238. if(rmi.getATerminal(Integer.parseInt(pedido))) {
  239. out.println("ID aceite!");
  240. for(Connection x:connections) {
  241. if(x.isLive()) {
  242. if(x.available==true) {
  243. out.println("Terminal "+x.thread_id+" is free.");
  244. out.println("Go to terminal "+x.thread_id);
  245. x.outStream.println("Terminal unblocked of CC: "+pedido+"\n Press enter to continue your request.");
  246. x.cc=pedido;
  247. x.available=false;
  248. break;
  249. }else {
  250. out.println("Terminal "+x.thread_id+" occupied.");
  251. }
  252. }else {
  253. connectionsDeleteCache.add(x);
  254. }
  255. }
  256. for(Connection x:connectionsDeleteCache) {
  257. connections.remove(x);
  258. }
  259. connectionsDeleteCache.clear();
  260. }else {
  261. out.println("Your cc does not exist");
  262. }
  263. }
  264. buffer.clear();
  265.  
  266. check=1;
  267. } catch (NotBoundException e1) {
  268. check=0;
  269. e1.printStackTrace();
  270. }catch(RemoteException e2) {
  271. check=0;
  272. }
  273. }
  274. }
  275. }
  276. }catch (IOException e) {
  277. System.out.println("IO:" + e);
  278. }
  279.  
  280. }
  281. public void addBuffer(String pedido) {
  282. int check=0;
  283. for(String x:buffer) {
  284. if(x.equals(pedido)) {
  285. check=1;
  286. }
  287. }
  288. if(check==0) {
  289. buffer.add(pedido);
  290. }else {
  291. System.out.println("Pedido descartado(duplicado)");
  292. }
  293.  
  294. }
  295.  
  296. public static int testOption(int minimo, int maximo) {
  297. Scanner inputS = new Scanner(System.in);
  298. int opcao = 0, test;
  299. String numero;
  300. while (true) {
  301. test = 0;
  302. try {
  303. while (test != 1) {
  304. try {
  305. out.print("\n[" + minimo + "-" + maximo + "]Chose:");
  306. numero = inputS.nextLine();
  307. opcao = Integer.parseInt(numero);
  308. test = 1;
  309. } catch (Exception e) {
  310. out.print("Escolha invalida!");
  311. }
  312. }
  313. if (opcao < minimo || opcao > maximo) {
  314. out.print("Escolha invalida!");
  315. } else {
  316. return opcao;
  317. }
  318. } catch (InputMismatchException exception) {
  319. out.print("Escolha invalida!");
  320. inputS.next();
  321. }
  322. }
  323.  
  324. }
  325. public static boolean checkNumbers(String num) {
  326. int i = 0;
  327. char[] array = num.toCharArray();
  328. while (num.length() != i) {
  329. if ((int) array[i] > 57 || (int) array[i] < 48) {
  330. out.println("Can not start or end with a space and can only ccontain numbers!");
  331. return false;
  332. }
  333. i++;
  334. }
  335. if (num.length() == 0) {
  336. out.println("Can not start or end with a space and can only ccontain numbers!");
  337. return false;
  338. }
  339. return true;
  340. }
  341. }
  342.  
  343. class Receiver extends Thread {
  344. public int myPort;
  345. public String rmiHost;
  346. public int rmiPort;
  347. public int thread_id = 0;
  348. ArrayList<Connection> connections;
  349. Mesas mesaVoto;
  350. RMI rmi;
  351. public Receiver(int myPort, String rmiHost, int rmiPort,ArrayList<Connection> connections,Mesas mesaVoto,RMI rmi) {
  352. this.myPort = myPort;
  353. this.rmiHost = rmiHost;
  354. this.rmiPort = rmiPort;
  355. this.connections=connections;
  356. this.mesaVoto=mesaVoto;
  357. this.rmi=rmi;
  358. this.start();
  359. }
  360.  
  361. public void run() {
  362. try {
  363. ServerSocket listenSocket = new ServerSocket(myPort);
  364. System.out.println("LISTEN SOCKET=" + listenSocket);
  365. while (true) {
  366. Socket clientSocket = listenSocket.accept(); // BLOQUEANTE
  367. System.out.println("CLIENT_SOCKET (created at accept())=" + clientSocket);
  368. thread_id++;
  369. connections.add(new Connection(clientSocket, connections, rmiHost, rmiPort, thread_id,mesaVoto,rmi));
  370. }
  371. }catch (EOFException e) {
  372. System.out.println("EOF:" + e);
  373. } catch (IOException e) {
  374. System.out.println("Listen:" + e.getMessage());
  375. }
  376.  
  377. }
  378. }
  379.  
  380. class Connection extends Thread {
  381. public BufferedReader inStream = null;
  382. public PrintWriter outStream;
  383. public Socket clientSocket;
  384. public String rmiHost;
  385. public int rmiPort;
  386. public int thread_id;
  387. public RMI rmi;
  388. public String cc;
  389. public boolean available;
  390. public boolean loggedIN;
  391. ArrayList<Connection> lista;
  392. Mesas mesaVoto;
  393. ArrayList<String> buffer;
  394.  
  395. public Connection(Socket aClientSocket, ArrayList<Connection> connections, String rmiHost, int rmiPort,int numero,Mesas mesaVoto,RMI rmi) {
  396. this.thread_id = numero;
  397. this.lista = connections;
  398. this.clientSocket = aClientSocket;
  399. this.rmiHost = rmiHost;
  400. this.rmiPort = rmiPort;
  401. this.mesaVoto=mesaVoto;
  402. this.buffer=new ArrayList<String>();
  403. cc=null;
  404. available=true;
  405. loggedIN=false;
  406. try {
  407. //this.rmi = (RMI) Naming.lookup("rmi://" + rmiHost + ":" + rmiPort + "/rmi");
  408. this.rmi=rmi;
  409. inStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  410. outStream = new PrintWriter(clientSocket.getOutputStream(), true);
  411. this.start();
  412. } catch (IOException e) {
  413. System.out.println("Connection:" + e.getMessage());
  414. }/* catch (NotBoundException e) {
  415. e.printStackTrace();
  416. }*/
  417. }
  418. public boolean isLive() {
  419. try {
  420. clientSocket.sendUrgentData(1);
  421. } catch (IOException e) {
  422. return false;
  423. }
  424. return true;
  425.  
  426.  
  427. /*if(clientSocket.getRemoteSocketAddress()==null) {
  428. System.out.println("adeus crlh");
  429. return true;
  430. }else {
  431. System.out.println("ola crlh");
  432. return false;
  433. }*/
  434. }
  435.  
  436. // =============================
  437. public void addBuffer(String s) {
  438. try {
  439. String pedido;
  440. HashMap<String, String> m = ProtocolParser.parse(s);
  441. pedido=m.get("type");
  442. int check=0;
  443. for(String x:buffer) {
  444. if(x.equals(pedido)) {
  445. check=1;
  446. }
  447. }
  448. if(check==0) {
  449. System.out.println(pedido);
  450. buffer.add(s);
  451. }else {
  452. System.out.println("Pedido descartado(duplicado)");
  453. }
  454. }catch (IllegalArgumentException e){
  455. System.out.println("type: error_message, IllegalArgumentException");
  456.  
  457. } catch (NullPointerException e) {
  458. System.out.println("type: error_message,NullPointerException");
  459.  
  460. } catch (ArrayIndexOutOfBoundsException e) {
  461. System.out.println("type: error_message, ArrayIndexOutOfBoundsException");
  462.  
  463. }catch (Exception e) {
  464. e.printStackTrace();
  465. }
  466.  
  467. }
  468. public void run() {
  469. String pedido="";
  470. int check=0;
  471. boolean state=true;
  472. boolean exception=true;
  473. while(exception) {
  474. if (available==false){
  475. try {
  476. clientSocket.setSoTimeout(120000);
  477. while(true) {
  478. pedido=inStream.readLine();
  479. try {
  480. HashMap<String, String> m = ProtocolParser.parse(pedido);
  481.  
  482. switch (m.get("type")) {
  483. case ("login"): {
  484. String username = m.get("username").equals(null) ? null : m.get("username");
  485. String password = m.get("password").equals(null) ? null : m.get("password");
  486. if (rmi.login(username, password)) {
  487. System.out.println("Login with sucess!");
  488. loggedIN = true;
  489. rmi.loginDone(cc,mesaVoto);
  490. } else {
  491. System.out.println("Username and Password do not correspond");
  492. }
  493. break;
  494. }
  495. case ("status"): {
  496. boolean status;
  497. status = rmi.status(cc);
  498. if (status) {
  499. outStream.println("Looged on");
  500. } else {
  501. outStream.println("Looged off");
  502. }
  503. break;
  504. }
  505. case ("elections"): {
  506. boolean status = rmi.status(cc);
  507. if (status) {
  508. System.out.println("hello");
  509. outStream.println(rmi.print_elections_for_person(cc,mesaVoto));
  510. } else {
  511. outStream.println("Looged off!");
  512. }
  513. break;
  514. }
  515. case ("vote"): {
  516. boolean status = rmi.status(cc);
  517. if (status) {
  518. String eleicao = m.get("election").equals(null) ? null : m.get("election");
  519. String list = m.get("list").equals(null) ? null : m.get("list");
  520. outStream.println(rmi.register_vote(cc, eleicao, list,mesaVoto));
  521. } else {
  522. outStream.println("Looged off");
  523. }
  524. break;
  525.  
  526. }
  527. default:{
  528. System.out.println("type: error_message, status: not enought arguments1");
  529. System.out.println("default");
  530. break;
  531. }
  532. }
  533.  
  534. }catch (RemoteException er) {
  535.  
  536. while(check==0) {
  537. System.out.println(pedido);
  538. addBuffer(pedido);
  539. try {
  540. pedido=inStream.readLine();
  541. rmi=(RMI) Naming.lookup("rmi://" + rmiHost + ":" + rmiPort + "/rmi");
  542. for(String x:buffer) {
  543. HashMap<String, String> m = ProtocolParser.parse(x);
  544.  
  545. switch (m.get("type")) {
  546. case ("login"): {
  547. String username = m.get("username").equals(null) ? null : m.get("username");
  548. String password = m.get("password").equals(null) ? null : m.get("password");
  549. if (rmi.login(username, password)) {
  550. System.out.println("Login with sucess!");
  551. loggedIN = true;
  552. rmi.loginDone(cc,mesaVoto);
  553. } else {
  554. System.out.println("Username and Password do not correspond");
  555. }
  556. break;
  557. }
  558. case ("status"): {
  559. boolean status;
  560. status = rmi.status(cc);
  561. if (status) {
  562. outStream.println("Looged on");
  563. } else {
  564. outStream.println("Looged off");
  565. }
  566. break;
  567. }
  568. case ("elections"): {
  569. boolean status = rmi.status(cc);
  570. if (status) {
  571. System.out.println("hello");
  572. outStream.println(rmi.print_elections_for_person(cc,mesaVoto));
  573. } else {
  574. outStream.println("Looged off!");
  575. }
  576. break;
  577. }
  578. case ("vote"): {
  579. boolean status = rmi.status(cc);
  580. if (status) {
  581. String eleicao = m.get("election").equals(null) ? null : m.get("election");
  582. String list = m.get("list").equals(null) ? null : m.get("list");
  583. outStream.println(rmi.register_vote(cc, eleicao, list,mesaVoto));
  584. } else {
  585. outStream.println("Looged off");
  586. }
  587. break;
  588.  
  589. }
  590. default:{
  591. System.out.println("type: error_message, status: not enought arguments1");
  592. System.out.println("default");
  593. break;
  594. }
  595. }
  596.  
  597. }
  598. check=1;
  599. buffer.clear();
  600. } catch (RemoteException er1) {
  601. System.out.println("olaola");
  602. check=0;
  603. }catch (ArrayIndexOutOfBoundsException e) {
  604. check=0;
  605. }catch (NotBoundException e1) {
  606. check=0;
  607. }catch (IOException e1) {
  608. check=0;
  609. e1.printStackTrace();
  610. }
  611. }
  612.  
  613. } catch (IllegalArgumentException e){
  614. System.out.println("type: error_message, status: wrong arguments1");
  615.  
  616. } catch (NullPointerException e) {
  617. System.out.println("type: error_message, status: wrong arguments");
  618.  
  619. } catch (ArrayIndexOutOfBoundsException e) {
  620. System.out.println("type: error_message, status: not enought arguments");
  621.  
  622. }catch (Exception e) {
  623. e.printStackTrace();
  624. }
  625. }
  626.  
  627. }catch (SocketTimeoutException ste) {
  628. System.out.println("Terminal"+thread_id+" blocked. More then 120 sec without request");
  629. available = true;
  630. buffer.clear();
  631. } catch (EOFException e) {
  632. System.out.println("EOF:" + e);
  633. exception=false;
  634. } catch (IOException e) {
  635. exception=false;
  636. System.out.println("IO:" + e);
  637. try {
  638. clientSocket.close();
  639. } catch (IOException e1) {
  640. e1.printStackTrace();
  641. }
  642. }
  643. }else {
  644. try {
  645. inStream.readLine();
  646. }catch (IOException e) {}
  647. }
  648. try {
  649. Thread.sleep(500);
  650. } catch (InterruptedException e) {
  651.  
  652. e.printStackTrace();
  653. }
  654. }
  655. }
  656.  
  657.  
  658. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement