Advertisement
Guest User

Untitled

a guest
Dec 19th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 27.22 KB | None | 0 0
  1. package RMI;
  2.  
  3. import java.io.*;
  4. import java.net.*;
  5. import java.rmi.*;
  6. import java.rmi.registry.*;
  7. import java.rmi.server.*;
  8. import java.util.*;
  9. import java.sql.*;
  10.  
  11. public class RMIServer extends UnicastRemoteObject implements RMIServerInterface {
  12. private static final long serialVersionUID = 1L;
  13.  
  14. private static Connection connection = null;
  15.  
  16. public RMIServer() throws RemoteException {
  17. super();
  18. }
  19.  
  20. // =================================================================================================================
  21.  
  22. // Verfica o departamento
  23. public boolean checkFaculdade(int facID) throws RemoteException{
  24. try {
  25. ResultSet rs = queryDB("SELECT faculdade_facid FROM mesa_de_voto WHERE faculdade_facid = "+facID+";");
  26. if(rs.next())
  27. return true;
  28. } catch (SQLException e) { }
  29. return false;
  30. }
  31.  
  32. // Adiciona User na BD
  33. public boolean registerUser(int numberID, String name, String password, String phone, String address, String expDate, int profession) throws RemoteException {
  34. if(updateDB("CALL add_user("+numberID+",'"+name+"','"+password+"','"+phone+"','"+address+"','"+expDate+"',"+profession+");"))
  35. return true;
  36. return false;
  37. }
  38.  
  39. // Associa Faculdade a User
  40. public boolean addUserFac(int numberID, int faculdadeID) throws RemoteException{
  41. if(updateDB("CALL add_user_faculdade("+numberID+","+faculdadeID+");"))
  42. return true;
  43. return false;
  44. }
  45.  
  46. // Edita dados User
  47. public void editUser(int numberID, String name, String password, String phone, String expDate, String address) throws RemoteException {
  48. if(!name.equals(""))
  49. updateDB("CALL edit_name("+numberID+",'"+name+"');");
  50. if(!password.equals(""))
  51. updateDB("CALL edit_password("+numberID+",'"+password+"');");
  52. if(!phone.equals(""))
  53. updateDB("CALL edit_phone("+numberID+",'"+phone+"');");
  54. if(!expDate.equals(""))
  55. updateDB("CALL edit_expdate("+numberID+",'"+expDate+"');");
  56. if(!address.equals(""))
  57. updateDB("CALL edit_address("+numberID+",'"+address+"');");
  58. }
  59.  
  60. // Apaga User e todos os seus dados
  61. public boolean deleteUser(int numberID) throws RemoteException{
  62. if(updateDB("CALL delete_user("+numberID+");"))
  63. return true;
  64. return false;
  65. }
  66.  
  67. // Adiciona Faculdade
  68. public boolean registerFac(String facName) throws RemoteException {
  69. if(updateDB("CALL add_faculdade('"+facName+"');"))
  70. return true;
  71. return false;
  72. }
  73.  
  74. // Adiciona Departamento
  75. public boolean registerDep(String depName, int facID) throws RemoteException{
  76. if(updateDB("CALL add_departamento('"+depName+"',"+facID+");"))
  77. return true;
  78. return false;
  79. }
  80.  
  81. // Adiciona Unidade Orgânica
  82. public boolean registerUnit(int facID) throws RemoteException {
  83. if(updateDB("CALL add_unit("+facID+");"))
  84. return true;
  85. return false;
  86. }
  87.  
  88. // Edita nome de uma Faculdade
  89. public boolean editFac(int facID, String facName) throws RemoteException{
  90. if(updateDB("CALL edit_faculdade("+facID+",'"+facName+"');"))
  91. return true;
  92. return false;
  93. }
  94.  
  95. // Edita nome de um Departamento
  96. public boolean editDep(int depID, String depName) throws RemoteException{
  97. if(updateDB("CALL edit_departamento("+depID+",'"+depName+"');"))
  98. return true;
  99. return false;
  100. }
  101.  
  102. // Elimina Faculdade
  103. public boolean deleteFac(int facID) throws RemoteException {
  104. if(updateDB("CALL delete_faculdade("+facID+");"))
  105. return true;
  106. return false;
  107. }
  108.  
  109. // Elimina Departamento
  110. public boolean deleteDep(int depID) throws RemoteException {
  111. if(updateDB("CALL delete_departamento("+depID+");"))
  112. return true;
  113. return false;
  114. }
  115.  
  116. // Elimina Unidade Organica
  117. public boolean deleteUnit(int facID) throws RemoteException {
  118. if(updateDB("CALL delete_unit("+facID+");"))
  119. return true;
  120. return false;
  121. }
  122.  
  123. // Adiciona Eleicao(Conselho Geral: adiciona uma mesa de voto em cada faculdade, Nucleos: adiciona uma mesa de voto na faculdade em questão)
  124. public boolean addEl(int eleicaoID, String title, String description, int type, String startDate, String endDate,int faculdadeID) throws RemoteException{
  125. if(updateDB("CALL add_eleicao("+eleicaoID+",'"+title+"','"+description+"',"+type+",'"+startDate+"','"+endDate+"',"+faculdadeID+");"))
  126. return true;
  127. return false;
  128. }
  129.  
  130. // Edita titulo e descricao de uma Eleicao por ID
  131. public boolean editELText(int eleicaoID, String title, String description) throws RemoteException{
  132. if(updateDB("CALL edit_eleicao_text("+eleicaoID+",'"+title+"','"+description+"');"))
  133. return true;
  134. return false;
  135. }
  136.  
  137. // Edita datas de uma Eleicao por ID
  138. public boolean editElDate(int eleicaoID, String startdate, String enddate) throws RemoteException{
  139. if(updateDB("CALL edit_eleicao_date("+eleicaoID+",'"+startdate+"','"+enddate+"');"))
  140. return true;
  141. return false;
  142. }
  143.  
  144. // Apaga Eleicao por ID
  145. public boolean deleteEL(int eleicaoID) throws RemoteException{
  146. if(updateDB("CALL delete_eleicao("+eleicaoID+");"))
  147. return true;
  148. return false;
  149. }
  150.  
  151. // Adiciona uma Lista Candidata a uma determinada eleicao
  152. public boolean addLista(String name, int type, int numvotes, int eleicaoID) throws RemoteException{
  153. if(updateDB("CALL add_lista_candidata('"+name+"',"+type+","+numvotes+","+eleicaoID+");"))
  154. return true;
  155. return false;
  156. }
  157.  
  158. // Associa User a uma lista
  159. public boolean addUserLista(int listid, int userid) throws RemoteException{
  160. if(updateDB("CALL add_lista_candidata_user("+listid+","+userid+");"))
  161. return true;
  162. return false;
  163.  
  164. }
  165.  
  166. // Elimina uma Lista Candidata por ID
  167. public boolean deleteLista(int listid) throws RemoteException{
  168. if(updateDB("CALL delete_lista_candidata("+listid+");"))
  169. return true;
  170. return false;
  171. }
  172.  
  173. // Adiciona Mesa de Voto
  174. public boolean addBooth(int facid, int electionid) throws RemoteException{
  175. if(updateDB("CALL add_mesa_de_voto("+facid+","+electionid+");"))
  176. return true;
  177. return false;
  178. }
  179.  
  180. // Apaga Mesa de Voto
  181. public boolean deleteBooth(int facid, int electionid) throws RemoteException{
  182. if(updateDB("CALL delete_mesa_de_voto("+facid+","+electionid+");"))
  183. return true;
  184. return false;
  185. }
  186.  
  187. // Acresenta User a uma Mesa de Voto
  188. public boolean addUserBooth(int userID, int facID , int electionID) throws RemoteException{
  189. try{
  190. ResultSet rs = queryDB("SELECT COUNT(*) FROM mesa_de_voto_user WHERE mesa_de_voto_faculdade_facid = "+facID+" AND mesa_de_voto_eleicao_electionid = "+electionID+";");
  191. if(rs.next()){
  192. if(rs.getInt("COUNT(*)")<3) {
  193. if (updateDB("call add_mesa_de_voto_user(" + userID + "," + facID + "," + electionID + ");"))
  194. return true;
  195. }
  196. }
  197. } catch (SQLException e){
  198. e.printStackTrace();
  199. }
  200. return false;
  201. }
  202.  
  203. // Remove User de uma Mesa de Voto
  204. public boolean removeUserBooth(int userID, int facID , int electionID) throws RemoteException{
  205. if(updateDB("call delete_mesa_de_voto_user("+userID+","+facID+","+electionID+");"))
  206. return true;
  207. return false;
  208. }
  209.  
  210. // Retorna tipo de Eleicao por ID
  211. public int getElectionType(int id) throws RemoteException{
  212. try {
  213. ResultSet rs = queryDB("SELECT type FROM eleicao WHERE electionid = "+id+";");
  214. if(rs.next())
  215. return rs.getInt("type");
  216. } catch (SQLException e) {
  217. e.printStackTrace();
  218. }
  219. return 0;
  220. }
  221.  
  222. // Retorna tipo de Lista por ID
  223. public int getListType(int id) throws RemoteException{
  224. try {
  225. ResultSet rs = queryDB("SELECT type FROM lista_candidata WHERE electionid = "+id+";");
  226. if(rs.next())
  227. return rs.getInt("type");
  228. } catch (SQLException e) {
  229. e.printStackTrace();
  230. }
  231. return 0;
  232. }
  233.  
  234. // Retorna tipo de User por ID
  235. public int getUserType(int id) throws RemoteException{
  236. ResultSet rs;
  237. try {
  238. rs = queryDB("SELECT * FROM estudante WHERE user_numberid = "+id+";");
  239. if(rs.next())
  240. return 1;
  241. rs = queryDB("SELECT * FROM professor WHERE user_numberid = "+id+";");
  242. if(rs.next())
  243. return 2;
  244. rs = queryDB("SELECT * FROM funcionario WHERE user_numberid = "+id+";");
  245. if(rs.next())
  246. return 3;
  247. } catch (SQLException e) {
  248. e.printStackTrace();
  249. }
  250. return 0;
  251. }
  252.  
  253. // Retorna ID de um user por nome
  254. public int getUserID(String name) throws RemoteException{
  255. try {
  256. ResultSet rs = queryDB("SELECT numberid FROM user WHERE name = '"+name+"';");
  257. if(rs.next())
  258. return rs.getInt("numberid");
  259. } catch (SQLException e) {
  260. e.printStackTrace();
  261. }
  262. return 0;
  263. }
  264.  
  265. // Retorna ID da lista por nome
  266. public int getListID(String name, int electionID) throws RemoteException{
  267. try {
  268. ResultSet rs = queryDB("SELECT listid FROM lista_candidata WHERE name = '"+name+"' AND eleicao_electionid = "+electionID+";");
  269. if(rs.next())
  270. return rs.getInt("listid");
  271. } catch (SQLException e) {
  272. e.printStackTrace();
  273. }
  274. return 0;
  275. }
  276.  
  277. // Verifica se eleicao ainda nao acabou
  278. public boolean elAntecipated(int electionID) throws RemoteException{
  279. try{
  280. ResultSet rs = queryDB("SELECT electionid FROM eleicao WHERE (enddate > CURRENT_TIMESTAMP) AND (startdate > CURRENT_TIMESTAMP) AND electionid = "+electionID+";");
  281. if(rs.next()){
  282. return true;
  283. }
  284. }catch (SQLException e){
  285. e.printStackTrace();
  286. }
  287. return false;
  288. }
  289.  
  290. // Verifica se eleicao ainda nao acabou
  291. public boolean elTerminated(int electionID) throws RemoteException{
  292. try{
  293. ResultSet rs = queryDB("SELECT electionid FROM eleicao WHERE (enddate < CURRENT_TIMESTAMP) AND electionid = "+electionID+";");
  294. if(rs.next()){
  295. return true;
  296. }
  297. }catch (SQLException e){
  298. e.printStackTrace();
  299. }
  300. return false;
  301. }
  302.  
  303. // Voto antecipado
  304. public boolean antecipatedVote(int userID, int electionID, int listID) throws RemoteException{
  305. if(updateDB("CALL antecipated_vote("+userID+","+electionID+","+listID+");"))
  306. return true;
  307. return false;
  308. }
  309.  
  310. // Retorna id maximo das eleicoes
  311. public ArrayList<Integer> getEls() throws RemoteException{
  312. ArrayList<Integer> aux = new ArrayList<>();
  313. try{
  314. ResultSet rs = queryDB("SELECT electionid FROM eleicao;");
  315. while (rs.next()){
  316. aux.add(rs.getInt("electionid"));
  317. }
  318. } catch (SQLException e){
  319. e.printStackTrace();
  320. }
  321. return aux;
  322. }
  323.  
  324. // Verifica se a eleicao ja acabou
  325. public boolean pastEl(int electionID) throws RemoteException{
  326. try {
  327. ResultSet rs = queryDB("SELECT electionid FROM eleicao WHERE enddate < CURRENT_TIMESTAMP AND electionid = "+electionID+";");
  328. if(rs.next())
  329. return true;
  330. } catch (SQLException e) {
  331. e.printStackTrace();
  332. }
  333. return false;
  334. }
  335.  
  336. // Retorna numero de votos numa lista
  337. public int getVotes(int listID) throws RemoteException{
  338. try {
  339. ResultSet rs = queryDB("SELECT numvotes FROM lista_candidata WHERE listid = "+listID+";");
  340. if(rs.next())
  341. return rs.getInt("numvotes");
  342. } catch (SQLException e) {
  343. e.printStackTrace();
  344. }
  345. return 0;
  346. }
  347.  
  348. // Retorna numero total de votos de uma eleicao
  349. public int getTotalVotes(int electionID) throws RemoteException{
  350. try {
  351. ResultSet rs = queryDB("SELECT SUM(numvotes) FROM lista_candidata WHERE eleicao_electionid = "+electionID+";");
  352. if(rs.next())
  353. return rs.getInt("SUM(numvotes)");
  354. } catch (SQLException e) {
  355. e.printStackTrace();
  356. }
  357. return 0;
  358.  
  359. }
  360.  
  361. // Retorna ID da faculdade onde utilizador votou
  362. public String getFaculdadeVoted(int userID, int electionID) throws RemoteException{
  363. try {
  364. ResultSet rs = queryDB("SELECT faculdade_facid FROM eleicao_user WHERE eleicao_electionid = "+electionID+" AND user_numberid = "+userID+";");
  365. if(rs.next()) {
  366. int aux = rs.getInt("faculdade_facid");
  367. return getFacName(aux);
  368. }
  369. } catch (SQLException e) {
  370. e.printStackTrace();
  371. }
  372. return "";
  373. }
  374.  
  375. // Retorna nome de faculade por ID
  376. public String getFacName(int facID){
  377. try {
  378. ResultSet rs = queryDB("SELECT name FROM faculdade WHERE facid = "+facID+";");
  379. if(rs.next())
  380. return rs.getString("name");
  381. } catch (SQLException e) {
  382. e.printStackTrace();
  383. }
  384. return "";
  385. }
  386.  
  387. // Log in User
  388. public boolean authenticateUser(String name, String password) throws RemoteException{
  389. try{
  390. ResultSet rs = queryDB("SELECT password FROM user WHERE name = '"+name+"';");
  391. if(rs.next()){
  392. if(rs.getString("password").equals(password))
  393. return true;
  394. }
  395. }catch (SQLException e){
  396. e.printStackTrace();
  397. }
  398. return false;
  399. }
  400.  
  401. // Retorna faculdades a que user pertence
  402. public boolean identifyID(int userID, int facID) throws RemoteException{
  403. try{
  404. ResultSet rs = queryDB("SELECT user_numberid,faculdade_facid FROM user_faculdade WHERE user_numberid = "+userID+" AND faculdade_facid = "+facID+";");
  405. if(rs.next()){
  406. return true;
  407. }
  408. }catch (SQLException e){
  409. e.printStackTrace();
  410. }
  411. return false;
  412. }
  413.  
  414. // Retorna faculdades a que user pertence
  415. public boolean identifyName(String name, int facID) throws RemoteException{
  416. try{
  417. ResultSet rs = queryDB("SELECT numberid FROM user WHERE name = '"+name+"';");
  418. if(rs.next()){
  419. ResultSet rs2 = queryDB("SELECT * FROM user_faculdade WHERE user_numberid = "+rs.getString("numberid"));
  420. while (rs2.next()){
  421. if(rs2.getInt("faculdade_facid")==facID)
  422. return true;
  423. }
  424. }
  425. }catch (SQLException e){
  426. e.printStackTrace();
  427. }
  428. return false;
  429. }
  430.  
  431. // Retorna eleicoes elegiveis para determinada faculdade
  432. public ArrayList<Integer> getMesaDeVotoEls(int facid) throws RemoteException{
  433. ArrayList<Integer> aux = new ArrayList<>();
  434. try{
  435. ResultSet rs = queryDB("SELECT eleicao_electionid FROM mesa_de_voto WHERE faculdade_facid = "+facid+";");
  436. while (rs.next()){
  437. aux.add(rs.getInt("eleicao_electionid"));
  438. }
  439. } catch (SQLException e){
  440. e.printStackTrace();
  441. }
  442. return aux;
  443. }
  444.  
  445. // Retorna id de todas as eleicoes
  446. public ArrayList<Integer> getElsID() throws RemoteException{
  447. ArrayList<Integer> aux = new ArrayList<>();
  448. try{
  449. ResultSet rs= queryDB("SELECT electionid FROM eleicao;");
  450. while (rs.next()){
  451. aux.add(rs.getInt("electionid"));
  452. }
  453. } catch (SQLException e){
  454. e.printStackTrace();
  455. }
  456. return aux;
  457. }
  458.  
  459. // Verifica se a eleicao está ativa
  460. public boolean isElActive (int electionID) throws RemoteException {
  461. try{
  462. ResultSet rs = queryDB("SELECT electionid FROM eleicao WHERE (startdate < CURRENT_TIMESTAMP) AND (enddate > CURRENT_TIMESTAMP) AND electionid = "+electionID+";");
  463. if(rs.next()){
  464. return true;
  465. }
  466. }catch (SQLException e){
  467. e.printStackTrace();
  468. }
  469. return false;
  470. }
  471.  
  472. // Regista Voto
  473. public boolean voteElection(int userID, int electionID, int listID, int facID) throws RemoteException {
  474. if(updateDB("CALL vote("+userID+","+electionID+","+listID+","+facID+");"))
  475. return true;
  476. return false;
  477. }
  478.  
  479. // Verifica se user já votou em eleição
  480. public boolean hasVoted(int userID, int electionID) throws RemoteException {
  481. try {
  482. ResultSet rs = queryDB("SELECT * FROM eleicao_user WHERE eleicao_electionid = "+electionID+" AND user_numberid = "+userID+";");
  483. if(rs.next())
  484. return true;
  485. } catch (SQLException e) { }
  486. return false;
  487. }
  488.  
  489. // Verifica se user já pode votar em determinada eleicao
  490. public boolean userCanVote (int userID, int electionID) throws RemoteException{
  491. int user = -1, eleicaoType = -1;
  492. try {
  493. ResultSet rs = queryDB("SELECT type FROM eleicao WHERE electionid = "+electionID+";");
  494. if(rs.next()) {
  495. eleicaoType = (rs.getInt("type"));
  496. if (eleicaoType == 2){
  497. rs = queryDB("SELECT user_numberid FROM estudante WHERE user_numberid= "+userID+";");
  498. if(rs.next()) return true;
  499. }
  500. else return true;
  501. }
  502. } catch (SQLException e) { }
  503. return false;
  504. }
  505.  
  506. // Retorna nome eleicao por ID
  507. public String getElName(int id) throws RemoteException{
  508. try{
  509. ResultSet rs = queryDB("SELECT title FROM eleicao WHERE electionid = "+id+";");
  510. if(rs.next()){
  511. return rs.getString("title");
  512. }
  513. }catch (SQLException e){ }
  514. return "";
  515. }
  516.  
  517. // Retorna dados de uma eleicao
  518. public ArrayList<String> getEl(int id) throws RemoteException{
  519. ArrayList<String> aux = new ArrayList<>();
  520. try{
  521. ResultSet rs = queryDB("SELECT title,description,startdate,enddate FROM eleicao WHERE electionid = "+id+";");
  522. if(rs.next()){
  523. aux.add(rs.getString("title"));
  524. aux.add(rs.getString("description"));
  525. aux.add(rs.getString("startdate"));
  526. aux.add(rs.getString("enddate"));
  527. }
  528. }catch (SQLException e){ }
  529. return aux;
  530. }
  531.  
  532. // Retorna listas elegiveis para determinada eleicao
  533. public ArrayList<Integer> getElectionLists(int electionid) throws RemoteException{
  534. ArrayList<Integer> aux = new ArrayList<>();
  535. try{
  536. ResultSet rs = queryDB("SELECT listid FROM lista_candidata WHERE eleicao_electionid = "+electionid+";");
  537. while (rs.next()){
  538. aux.add(rs.getInt("listid"));
  539. }
  540. } catch (SQLException e){ }
  541. return aux;
  542. }
  543.  
  544. // Retorna nome lista por ID
  545. public String getListName(int id, int eleicaoid) throws RemoteException{
  546. try{
  547. ResultSet rs = queryDB("SELECT name FROM lista_candidata WHERE listid = "+id+" AND eleicao_electionid = "+eleicaoid+";");
  548. if(rs.next()){
  549. return rs.getString("name");
  550. }
  551. }catch (SQLException e){ }
  552. return "";
  553. }
  554.  
  555. public int getElectionID(String name) throws RemoteException{
  556. try {
  557. ResultSet rs = queryDB("SELECT electionid FROM eleicao WHERE title = '"+name+"';");
  558. if(rs.next())
  559. return rs.getInt("electionid");
  560. } catch (SQLException e) {
  561. e.printStackTrace();
  562. }
  563. return 0;
  564. }
  565.  
  566. // =================================================================================================================
  567. // Main
  568. public static void main(String args[]) {
  569. Scanner sc = new Scanner(System.in);
  570. RMIFailover UDPConn;
  571.  
  572. String hostname;
  573. int rmiPort, defPort;
  574.  
  575. System.out.println("RMI Hostname: ");
  576. hostname = sc.nextLine();
  577.  
  578. System.out.println("RMI Port");
  579. rmiPort = sc.nextInt();
  580.  
  581. System.out.println("UPDSocket Port");
  582. defPort = sc.nextInt();
  583.  
  584. // Inicia thread que lida com a conexão UDP
  585. UDPConn = new RMIFailover(hostname, defPort, rmiPort);
  586. UDPConn.start();
  587. }
  588.  
  589. // Seleciona se vai ser Main ou Backup RMI
  590. public void startRMI(int rmiPort) {
  591. if (connectDB()) {
  592. try {
  593. // Criação RMI
  594. RMIServer server = new RMIServer();
  595. Registry reg = LocateRegistry.createRegistry(rmiPort);
  596. reg.rebind("vote_booth", server);
  597. System.out.println("RMI Server connected");
  598. } catch(RemoteException e){
  599. System.out.println("Could not bind RMI registry");
  600. }
  601. }
  602. }
  603.  
  604. // Cria conneção à base de dados
  605. public static boolean connectDB(){
  606. try{
  607. Class.forName("com.mysql.jdbc.Driver");
  608. } catch (ClassNotFoundException e) {
  609. System.out.println("JDBC Driver not found");
  610. return false;
  611. }
  612. connection = null;
  613. try{
  614. connection = DriverManager.getConnection(
  615. "jdbc:mysql://127.0.0.1:3306/sdProjectDatabase?autoReconnect=true&useSSL=false",
  616. "bd_user",
  617. "password");
  618. } catch (SQLException e) {
  619. System.err.println("Database connection failed");
  620. return false;
  621. }
  622. System.out.println("Connected to database");
  623. return true;
  624. }
  625.  
  626. // Executa update à base de dados
  627. public static boolean updateDB(String str){
  628. try {
  629. Statement stmt;
  630. if (connection.createStatement() == null) {
  631. connection = DriverManager.getConnection(
  632. "jdbc:mysql://127.0.0.1:3306/sdProjectDatabase",
  633. "bd_user",
  634. "password");
  635. }
  636. if ((stmt = connection.createStatement()) == null) {
  637. System.err.println("Error creating statement");
  638. }
  639. stmt.executeUpdate(str);
  640. }catch (SQLException e){
  641. System.err.println("Error executing "+str);
  642. e.printStackTrace();
  643. return false;
  644. }
  645. System.out.println("Success executing "+str);
  646. return true;
  647. }
  648.  
  649. // Executa query à base de dados
  650. public static ResultSet queryDB(String str){
  651. try {
  652. Statement stmt;
  653. if (connection.createStatement() == null) {
  654. connection = DriverManager.getConnection(
  655. "jdbc:mysql://127.0.0.1:3306/sdProjectDatabase",
  656. "bd_user",
  657. "password");
  658. }
  659. if ((stmt = connection.createStatement()) == null) {
  660. System.err.println("Error creating statement");
  661. }
  662. return stmt.executeQuery(str);
  663. }catch (SQLException e){
  664. System.err.println("Error executing "+str);
  665. }
  666. System.out.println("Success executing "+str);
  667. return null;
  668. }
  669. }
  670.  
  671. // Thread que trata do Failover
  672. class RMIFailover extends Thread {
  673. private DatagramSocket aSocket = null;
  674.  
  675. private String hostname;
  676. private int serverPort, rmiPort;
  677.  
  678. public RMIFailover(String hostname, int serverPort, int rmiPort) {
  679. this.hostname = hostname;
  680. this.serverPort = serverPort;
  681. this.rmiPort = rmiPort;
  682. }
  683.  
  684. public void run() {
  685. RMIFailover UDPConn;
  686. try {
  687. // Abre socket UDP
  688. this.aSocket = new DatagramSocket(this.serverPort);
  689.  
  690. RMIServer RMIServer = new RMIServer();
  691. RMIServer.startRMI(this.rmiPort);
  692.  
  693. while (true) {
  694. String texto = "";
  695. byte[] m = texto.getBytes();
  696.  
  697. // Cria e envia pacote UDP
  698. InetAddress aHost = InetAddress.getByName(this.hostname);
  699. DatagramPacket request = new DatagramPacket(m, m.length, aHost, this.serverPort);
  700. aSocket.send(request);
  701.  
  702. try {
  703. Thread.sleep(1000);
  704. } catch (InterruptedException i) {
  705. }
  706. }
  707.  
  708. } catch (SocketException e) {
  709. System.out.println("Backup RMI Server started");
  710. int heartbeatsFailed = 0, maxHeartbeats = 5;
  711. byte[] buffer = new byte[1000];
  712.  
  713. try {
  714. // Abre receiver socket UDP
  715. this.aSocket = new DatagramSocket(null);
  716. this.aSocket.setReuseAddress(true);
  717. this.aSocket.bind(new InetSocketAddress(this.hostname, this.serverPort));
  718. while (heartbeatsFailed < maxHeartbeats) {
  719. // Define timeout de recepção de heartbeat
  720. this.aSocket.setSoTimeout(1500);
  721.  
  722. InetAddress aHost = InetAddress.getByName(this.hostname);
  723.  
  724. // Cria e recebe pacote UDP
  725. DatagramPacket request = new DatagramPacket(buffer, buffer.length, aHost, this.serverPort);
  726. try {
  727. aSocket.receive(request);
  728. System.out.println("Received heartbeat from Main RMI server");
  729. } catch (SocketTimeoutException i){
  730. heartbeatsFailed++;
  731. System.err.println("Did not receive heartbeat from Main RMI server\tRetrying... "+heartbeatsFailed+"/"+maxHeartbeats);
  732. }
  733. }
  734.  
  735. if(heartbeatsFailed >= maxHeartbeats) {
  736. this.aSocket.close();
  737. UDPConn = new RMIFailover(this.hostname, this.serverPort, this.rmiPort);
  738. UDPConn.start();
  739. try {
  740. Thread.currentThread().join();
  741. } catch (InterruptedException i) {
  742. }
  743. }
  744.  
  745. } catch (SocketException i) { System.out.println("Socket: " + e.getMessage());
  746. } catch (IOException i) { System.out.println("IO: " + e.getMessage());
  747. } finally { if (this.aSocket != null) this.aSocket.close(); }
  748.  
  749. } catch (IOException e) { System.out.println("IO: " + e.getMessage());
  750. } finally { if (this.aSocket != null) this.aSocket.close(); }
  751. }
  752. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement