Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 53.20 KB | None | 0 0
  1. package iBei.rmi;
  2.  
  3. import iBei.aux.FicheiroDeObjeto;
  4. import iBei.aux.Leilao;
  5. import iBei.aux.User;
  6. import iBei.server.TCP_Interface;
  7.  
  8. import java.io.File;
  9. import java.io.IOException;
  10. import java.rmi.NotBoundException;
  11. import java.rmi.RemoteException;
  12. import java.rmi.registry.LocateRegistry;
  13. import java.rmi.registry.Registry;
  14. import java.rmi.server.UnicastRemoteObject;
  15. import java.sql.*;
  16. import java.text.DateFormat;
  17. import java.text.ParseException;
  18. import java.text.SimpleDateFormat;
  19. import java.util.ArrayList;
  20. import java.util.Collections;
  21. import java.util.LinkedHashMap;
  22. import java.util.List;
  23.  
  24. class dbConnection{
  25. public Connection connection;
  26. public int estado;
  27. public int posicaoArray;
  28.  
  29. public dbConnection(Connection connection, int estado, int posicaoArray) {
  30. this.connection = connection;
  31. this.estado = estado;
  32. this.posicaoArray = posicaoArray;
  33. try {
  34. this.connection.setAutoCommit(false);
  35. } catch (SQLException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. }
  40.  
  41. public class RMI_Server extends UnicastRemoteObject implements RMI_Interface {
  42. //private List<Leilao> leiloes;
  43. //private List<User> registados;
  44. //private static List<User> loggados;
  45. private static List<TCP_Interface> tcpServers;
  46. private static String primaryRmi [] = new String[2];
  47. private static String backupRmi [] = new String[2];
  48. public static String dbHost;
  49. static int count = 0;
  50. public static ArrayList <dbConnection> connections = new ArrayList<>();
  51.  
  52.  
  53. public RMI_Server() throws RemoteException {
  54. super();
  55. try {
  56. Class.forName("com.mysql.jdbc.Driver");
  57. String connectionString = "jdbc:mysql://"+dbHost+":3306/bd";
  58. //System.out.println("Connecting to BD on host: "+dbHost);
  59. int i;
  60. for(i=0; i< 5; i++){
  61. connections.add(new dbConnection(DriverManager.getConnection(connectionString, "root", "root"),0,i));
  62. }
  63.  
  64. } catch (ClassNotFoundException | SQLException e) {
  65. e.printStackTrace();
  66. System.out.println("DATABASE OFFLINE.");
  67. System.exit(1);
  68. }
  69.  
  70. //leiloes = Collections.synchronizedList(new ArrayList<Leilao>());
  71. //registados = Collections.synchronizedList(new ArrayList<User>());
  72. //loggados = Collections.synchronizedList(new ArrayList<User>());
  73. tcpServers = Collections.synchronizedList(new ArrayList<TCP_Interface>());
  74. }
  75.  
  76. public dbConnection getConnection(){
  77. for(int i = 0; i< connections.size(); i++){
  78. if(connections.get(i).estado == 0){
  79. connections.get(i).estado = 1;
  80. return connections.get(i);
  81. }
  82.  
  83. }
  84. //adiciona caso nao haja nenhuma disponivel
  85. addConnection();
  86. return connections.get(connections.size()-1);
  87.  
  88. }
  89.  
  90. public void addConnection(){
  91. try {
  92. Class.forName("com.mysql.jdbc.Driver");
  93. String connectionString = "jdbc:mysql://"+dbHost+":3306/bd";
  94. connections.add(new dbConnection(DriverManager.getConnection(connectionString, "root", "root"),0,connections.size()-1));
  95. } catch (ClassNotFoundException e) {
  96. e.printStackTrace();
  97. } catch (SQLException e) {
  98. e.printStackTrace();
  99. }
  100.  
  101. }
  102.  
  103. public void releaseConnection(dbConnection c){
  104. for(int i = 0; i< connections.size(); i++){
  105. if(i == connections.get(i).posicaoArray){
  106. connections.get(i).estado = 0;
  107. }
  108. }
  109. }
  110.  
  111. public void addTCP(TCP_Interface tcp) throws RemoteException {
  112. tcpServers.add(tcp);
  113. //this.exportObjTCPServers();
  114. }
  115.  
  116. public boolean register_client(LinkedHashMap<String, String> data) throws RemoteException {
  117. System.out.println("[ REGISTER CLIENT ]");
  118. ArrayList <User> users = new ArrayList<>();
  119.  
  120. dbConnection c = getConnection();
  121. Connection connection = c.connection;
  122.  
  123. PreparedStatement statement = null;
  124. String username = data.get("username");
  125. String password = data.get("password");
  126. String query = "SELECT * FROM user WHERE user.username = ?;";
  127.  
  128. try {
  129. statement = connection.prepareStatement(query);
  130. statement.setString(1, username);
  131. ResultSet response = statement.executeQuery();
  132. users = getArraylistUsers(response, connection);
  133. if(users.size()!=0){
  134. System.out.println(users.size());
  135. return false;
  136. }
  137. } catch (SQLException e) {
  138. e.printStackTrace();
  139. return false;
  140. }
  141.  
  142. query= "INSERT INTO user (username, password, banido, leiloes, vitorias, logado) VALUES (?, ? ,false ,0,0,false);";
  143.  
  144. try {
  145. statement = connection.prepareStatement(query);
  146. statement.setString(1,username);
  147. statement.setString(2,password);
  148. System.out.println(statement.execute());
  149. connection.commit();
  150.  
  151. } catch (SQLException e) {
  152.  
  153. System.out.println("Rollback");
  154. try {
  155. connection.rollback();
  156. } catch (SQLException e1) {
  157. System.out.println("Error doing rollback!");
  158. }
  159. e.printStackTrace();
  160.  
  161. }
  162. releaseConnection(c);
  163. return true;
  164. }
  165.  
  166.  
  167. //TODO: TEMOS DE VER EM QUE CASOS TEMOS DE FAZER SELECT ... FOR UPDATE(slides)
  168. public boolean login_client(LinkedHashMap<String, String> data) throws RemoteException {
  169. //DEVEMOS RETORNAR O PROBLEMA??
  170. System.out.println("[ LOGIN CLIENT ] ");
  171. ArrayList <User> users = new ArrayList<>();
  172.  
  173. dbConnection c = getConnection();
  174. Connection connection = c.connection;
  175.  
  176. PreparedStatement statement = null;
  177. String username = data.get("username");
  178. String password = data.get("password");
  179. String query = "SELECT * FROM user WHERE user.username = ? AND user.password = ? AND user.banido = false AND user.logado = false;";
  180. try {
  181. statement = connection.prepareStatement(query);
  182. statement.setString(1, username);
  183. statement.setString(2, password);
  184. ResultSet response = statement.executeQuery();
  185. users = getArraylistUsers(response, connection);
  186. if(users.size()!=1)
  187. return false;
  188.  
  189.  
  190. } catch (SQLException e) {
  191. System.out.println("Rollback");
  192. try {
  193. connection.rollback();
  194. } catch (SQLException e1) {
  195. System.out.println("Error doing rollback!");
  196. }
  197. e.printStackTrace();
  198. return false;
  199. }
  200.  
  201. query= "UPDATE user SET logado = TRUE WHERE username = ?;";
  202.  
  203. try {
  204. statement = connection.prepareStatement(query);
  205. statement.setString(1,username);
  206. Boolean result = statement.execute();
  207. System.out.println("LOGIN: "+result);
  208. connection.commit();
  209.  
  210. } catch (SQLException ex) {
  211. System.out.println("Rollback");
  212. try {
  213. connection.rollback();
  214. } catch (SQLException e1) {
  215. System.out.println("Error doing rollback!");
  216. }
  217. ex.printStackTrace();
  218.  
  219. }
  220.  
  221. releaseConnection(c);
  222. return true;
  223.  
  224. }
  225.  
  226. public boolean logoutClient(String username) throws RemoteException {
  227. PreparedStatement statement = null;
  228.  
  229.  
  230. dbConnection c = getConnection();
  231. Connection connection = c.connection;
  232.  
  233. ArrayList <User> users = new ArrayList<>();
  234. String query = "SELECT * FROM user WHERE user.username = ? AND user.logado = true;";
  235. try {
  236. statement = connection.prepareStatement(query);
  237. statement.setString(1, username);
  238. ResultSet response = statement.executeQuery();
  239. users = getArraylistUsers(response,connection);
  240. if(users.size()!=1)
  241. return false;
  242.  
  243.  
  244. } catch (SQLException e) {
  245. e.printStackTrace();
  246. }
  247.  
  248. query= "UPDATE user SET logado = FALSE WHERE username = ?;";
  249.  
  250. try {
  251. statement = connection.prepareStatement(query);
  252. statement.setString(1,username);
  253. Boolean result = statement.execute();
  254. System.out.println("LOGOUT: "+result);
  255. connection.commit();
  256.  
  257. } catch (SQLException ex) {
  258. System.out.println("Rollback");
  259. try {
  260. connection.rollback();
  261. } catch (SQLException e1) {
  262. System.out.println("Error doing rollback!");
  263. }
  264. ex.printStackTrace();
  265.  
  266. }
  267. releaseConnection(c);
  268. return true;
  269. }
  270.  
  271. public boolean create_auction(LinkedHashMap<String, String> data, String username) throws RemoteException{
  272.  
  273. //parse data
  274. String query;
  275.  
  276. dbConnection c = getConnection();
  277. Connection connection = c.connection;
  278.  
  279. PreparedStatement statement = null;
  280. try {
  281. String code = data.get("code");
  282. double amount = Double.parseDouble(data.get("amount"));
  283. String titulo = data.get("title");
  284. String descricao = data.get("description");
  285. DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  286. java.util.Date date = d1.parse(data.get("deadline"));
  287.  
  288. query = "INSERT into leilao (username, artigoid, leilaoid, titulo, descricao, data, data_inicio, precomax, estado) VALUES (?, ?, null, ?, ?, ?, NOW(), ?, 0)";
  289.  
  290. statement = null;
  291.  
  292.  
  293. statement = connection.prepareStatement(query);
  294. statement.setString(1,username);
  295. statement.setString(2,code);
  296. statement.setString(3,titulo);
  297. statement.setString(4,descricao);
  298. statement.setTimestamp(5, new Timestamp(date.getTime()));
  299. statement.setDouble(6,amount);
  300. statement.execute();//return true or false
  301. connection.commit();
  302.  
  303. } catch (SQLException e) {
  304. System.out.println("Rollback");
  305. try {
  306. connection.rollback();
  307. } catch (SQLException e1) {
  308. System.out.println("Error doing rollback!");
  309. }
  310. e.printStackTrace();
  311. return false;
  312. } catch (ParseException e) {
  313. //e.printStackTrace();
  314. System.out.println("Date format invalid, it must be like: yyyy-MM-dd HH:mm:ss");
  315. return false;
  316. }
  317.  
  318.  
  319. query= "UPDATE user SET leiloes = leiloes +1 WHERE username = ?;";
  320.  
  321. try {
  322. statement = connection.prepareStatement(query);
  323. statement.setString(1,username);
  324. System.out.println(statement.execute());//return true or false
  325. connection.commit();
  326.  
  327. } catch (SQLException e) {
  328. System.out.println("Rollback");
  329. try {
  330. connection.rollback();
  331. } catch (SQLException e1) {
  332. System.out.println("Error doing rollback!");
  333. }
  334. e.printStackTrace();
  335.  
  336.  
  337. }
  338.  
  339. releaseConnection(c);
  340. return true;
  341. }
  342.  
  343. public ArrayList <Leilao> search_auction(LinkedHashMap<String, String> data) throws RemoteException {
  344.  
  345. String query = "SELECT * FROM leilao WHERE artigoid=?;";
  346. String code = data.get("code");
  347. PreparedStatement statement = null;
  348.  
  349. dbConnection c = getConnection();
  350. Connection connection = c.connection;
  351.  
  352. try {
  353. statement = connection.prepareStatement(query);
  354. statement.setString(1,code);
  355. ResultSet response = statement.executeQuery();
  356. /* System.out.println("Response: ");
  357. while(response.next())
  358. System.out.println(response.getLong("leilaoid"));
  359. */
  360. return (getArraylistLeiloes(response, connection));
  361.  
  362. } catch (SQLException e) {
  363. System.out.println("Rollback");
  364. try {
  365. connection.rollback();
  366. } catch (SQLException e1) {
  367. System.out.println("Error doing rollback!");
  368. }
  369. e.printStackTrace();
  370. }
  371.  
  372. releaseConnection(c);
  373. return null;
  374.  
  375. }
  376.  
  377.  
  378. public Leilao detail_auction(LinkedHashMap<String, String> data) throws RemoteException{
  379. System.out.println("[ DETAIL_AUCTION ]");
  380. String script = "SELECT leilao.leilaoid leilaoid, leilao.username username, leilao.artigoid artigoid, leilao.titulo titulo, leilao.descricao descricao, leilao.precomax precomax, leilao.data data FROM leilao WHERE leilaoid = ?;";
  381. PreparedStatement statement = null;
  382.  
  383. dbConnection c = getConnection();
  384. Connection connection = c.connection;
  385.  
  386. ArrayList <Leilao> resp = new ArrayList<>();
  387. try {
  388. statement = connection.prepareStatement(script);
  389. statement.setInt(1, Integer.parseInt(data.get("id")));
  390. ResultSet response = statement.executeQuery();
  391.  
  392. resp = getArraylistLeiloes(response, connection);
  393. if(resp.size() == 1)
  394. return (resp.get(0));
  395.  
  396. } catch (SQLException e) {
  397. System.out.println("Rollback");
  398. try {
  399. connection.rollback();
  400. } catch (SQLException e1) {
  401. System.out.println("Error doing rollback!");
  402. }
  403. e.printStackTrace();
  404. }
  405.  
  406. releaseConnection(c);
  407. return null;
  408. }
  409.  
  410. public ArrayList <Leilao> my_auctions(LinkedHashMap<String, String> data, String username) throws RemoteException{
  411. System.out.println("[ MY_AUCTIONS ]");
  412.  
  413. dbConnection c = getConnection();
  414. Connection connection = c.connection;
  415.  
  416. String query = "SELECT leilao.leilaoid leilaoid, leilao.username username, leilao.artigoid artigoid, leilao.titulo titulo, leilao.descricao descricao, leilao.precomax precomax, leilao.data data FROM leilao, ("+
  417. " SELECT licitacao.leilaoid id FROM licitacao WHERE licitacao.username = ?"+
  418. " UNION"+
  419. " SELECT mensagem.leilaoid id FROM mensagem WHERE mensagem.username = ?"+
  420. " UNION"+
  421. " SELECT leilao.leilaoid id FROM leilao WHERE username = ?) idLeiloes "+
  422. "WHERE idLeiloes.id = leilao.leilaoid";
  423.  
  424. PreparedStatement statement = null;
  425. try {
  426. statement = connection.prepareStatement(query);
  427. statement.setString(1,username);
  428. statement.setString(2,username);
  429. statement.setString(3,username);
  430. ResultSet response = statement.executeQuery();
  431. System.out.println("Response: ");
  432. /*while(response.next())
  433. System.out.println(response.getInt("leilaoid"));
  434. */
  435. return (getArraylistLeiloes(response, connection));
  436. } catch (SQLException e) {
  437. System.out.println("Rollback");
  438. try {
  439. connection.rollback();
  440. } catch (SQLException e1) {
  441. System.out.println("Error doing rollback!");
  442. }
  443. e.printStackTrace();
  444. }
  445.  
  446. releaseConnection(c);
  447. return null;
  448.  
  449. }
  450.  
  451. public ArrayList <Leilao> getArraylistLeiloes(ResultSet response, Connection connection){
  452. ArrayList <Leilao> leiloes = new ArrayList<>();
  453. PreparedStatement statement;
  454.  
  455. try {
  456. while(response.next()) {
  457. Timestamp date = response.getTimestamp("data");
  458. DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  459. String d = d1.format(date);
  460. int leilaoId = response.getInt("leilaoid");
  461. java.util.Date data = d1.parse(d);
  462. System.out.println(response.getInt("leilaoid"));
  463. Leilao leilao = new Leilao(response.getString("username"),response.getString("artigoid"),response.getString("titulo"),response.getString("descricao"),response.getDouble("precomax"),data, leilaoId);
  464.  
  465. String queryBids = "SELECT licitacao.username username, licitacao.quantia amount FROM licitacao WHERE licitacao.leilaoid = ?;";
  466.  
  467. statement = connection.prepareStatement(queryBids);
  468. statement.setInt(1, leilaoId);
  469. ResultSet result = statement.executeQuery();
  470. while(result.next()) {
  471. LinkedHashMap<String, String> my_bid = new LinkedHashMap<String, String>();
  472. my_bid.put("author", result.getString("username"));
  473. my_bid.put("bid", String.valueOf(result.getDouble("amount")));
  474. leilao.licitacoes.add(my_bid);
  475.  
  476. }
  477.  
  478. String queryMessages = "SELECT mensagem.username username, mensagem.texto text FROM mensagem WHERE mensagem.leilaoid = ?;";
  479.  
  480. statement = connection.prepareStatement(queryMessages);
  481. statement.setInt(1, leilaoId);
  482. result = statement.executeQuery();
  483. while(result.next()) {
  484. LinkedHashMap<String, String> my_message = new LinkedHashMap<String, String>();
  485. my_message.put("author", result.getString("username"));
  486. my_message.put("message", result.getString("text"));
  487. leilao.mensagens.add(my_message);
  488.  
  489. }
  490. leilao.printInfo();
  491. leiloes.add(leilao);
  492. }
  493.  
  494. } catch (SQLException e) {
  495. System.out.println("Rollback");
  496. try {
  497. connection.rollback();
  498. } catch (SQLException e1) {
  499. System.out.println("Error doing rollback!");
  500. }
  501. e.printStackTrace();
  502. } catch (ParseException e) {
  503. e.printStackTrace();
  504. }
  505.  
  506.  
  507. return leiloes;
  508. }
  509.  
  510. public ArrayList <User> getArraylistUsers(ResultSet response, Connection connection){
  511. ArrayList <User> users = new ArrayList<>();
  512.  
  513. try {
  514. while(response.next()) {
  515. users.add(new User(response.getString("username"), "default"));
  516. }
  517.  
  518. } catch (SQLException e) {
  519. System.out.println("Rollback");
  520. try {
  521. connection.rollback();
  522. } catch (SQLException e1) {
  523. System.out.println("Error doing rollback!");
  524. }
  525. e.printStackTrace();
  526. }
  527.  
  528.  
  529. return users;
  530. }
  531.  
  532.  
  533.  
  534. public boolean edit_auction(LinkedHashMap<String, String> data, String username) throws RemoteException {
  535. //TRATAR DE AUTO INCREMENT NA VERSAO
  536. System.out.println("[ EDIT AUCTION ]");
  537. PreparedStatement statement = null;
  538. Boolean result = false;
  539.  
  540. dbConnection c = getConnection();
  541. Connection connection = c.connection;
  542.  
  543. int count=1;
  544. boolean title = false, descricao= false, date= false, precoMax= false;
  545.  
  546. String query = "UPDATE leilao "
  547. +"SET ";
  548.  
  549. if (data.containsKey("title")) {
  550. query += "titulo = ?, ";
  551. title = true;
  552. }
  553. if (data.containsKey("description")) {
  554. query += "descricao = ?, ";
  555. descricao = true;
  556. }
  557. if (data.containsKey("deadline")) {
  558. query += "data = ?, ";
  559. date = true;
  560. }
  561. if (data.containsKey("amount")) {
  562. query += "precomax = ?, ";
  563. precoMax = true;
  564. }
  565. if(!title && !descricao && !date && !precoMax) {
  566. return false;
  567. }
  568.  
  569.  
  570. String insert = "INSERT INTO historico (leilaoid, versaoid, titulo, descricao, data, precomax)" +
  571. " SELECT l.leilaoid, 0, l.titulo, l.descricao, l.data, l.precomax FROM leilao l" +
  572. " WHERE l.leilaoid = ? AND l.username = ?;";
  573.  
  574.  
  575. try {
  576. statement = connection.prepareStatement(insert);
  577. statement.setLong(1, Long.parseLong(data.get("id")));
  578. statement.setString(2,username);
  579. if(statement.executeUpdate() <= 0){
  580. System.out.println("Something is wrong");
  581. return false;
  582. }
  583. } catch (SQLException e) {
  584. System.out.println("Rollback");
  585. try {
  586. connection.rollback();
  587. } catch (SQLException e1) {
  588. System.out.println("Error doing rollback!");
  589. }
  590. e.printStackTrace();
  591. }
  592.  
  593.  
  594.  
  595.  
  596. query = query.substring(0, query.lastIndexOf(","));
  597. query += " WHERE leilaoid = ?;";
  598.  
  599. try {
  600. statement = connection.prepareStatement(query);
  601. if(title){
  602. statement.setString(count,data.get("title"));
  603. count++;
  604. }
  605. if(descricao){
  606. statement.setString(count,data.get("description"));
  607. count++;
  608. }
  609. if(date){
  610. DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  611. java.util.Date d = d1.parse(data.get("deadline"));
  612. statement.setTimestamp(count, new Timestamp(d.getTime()));
  613. count++;
  614. }
  615. if(precoMax){
  616. statement.setDouble(count, Double.parseDouble(data.get("amount")));
  617. count++;
  618. }
  619.  
  620. System.out.println(query);
  621. statement.setString(count,data.get("id"));
  622. result = statement.execute();
  623. connection.commit();
  624.  
  625. } catch (SQLException e) {
  626. System.out.println("Rollback");
  627. try {
  628. connection.rollback();
  629. } catch (SQLException e1) {
  630. System.out.println("Error doing rollback!");
  631. }
  632. e.printStackTrace();
  633. } catch (ParseException e) {
  634. System.out.println("date format invalid!");
  635. System.out.println("Rollback");
  636. try {
  637. connection.rollback();
  638. } catch (SQLException e1) {
  639. System.out.println("Error doing rollback!");
  640. }
  641. e.printStackTrace();
  642. }
  643.  
  644. releaseConnection(c);
  645. return true;
  646. }
  647.  
  648. public List<User> listOnlineUsers() throws RemoteException {
  649. String query = "SELECT * FROM user WHERE logado=true;";
  650.  
  651. dbConnection c = getConnection();
  652. Connection connection = c.connection;
  653.  
  654. PreparedStatement statement = null;
  655. try {
  656. statement = connection.prepareStatement(query);
  657. ResultSet response = statement.executeQuery();
  658. return getArraylistUsers(response, connection);
  659.  
  660. } catch (SQLException e) {
  661. System.out.println("Rollback");
  662. try {
  663. connection.rollback();
  664. } catch (SQLException e1) {
  665. System.out.println("Error doing rollback!");
  666. }
  667. e.printStackTrace();
  668. }
  669.  
  670. releaseConnection(c);
  671. return null;
  672. }
  673.  
  674.  
  675. public Leilao make_bid(LinkedHashMap<String, String> data, String username) throws RemoteException {
  676. //FAZER BLOQUEIO A FUNCAO??
  677. //INFORMAR O QUE E QUE FALHOU??
  678. //NECESSIDADE DATAS ??
  679. //TODO:VERIFICACAO DE VALIDADE DE BID CORRETA(if...,max()...)??
  680.  
  681. dbConnection c = getConnection();
  682. Connection connection = c.connection;
  683.  
  684. ArrayList <Leilao> aux = new ArrayList<>();
  685. Long id = Long.parseLong(data.get("id"));
  686. Double amount = Double.parseDouble(data.get("amount"));
  687. System.out.println("amount: "+amount);
  688. PreparedStatement statement = null;
  689. String query = "SELECT * FROM leilao " +
  690. "WHERE leilao.leilaoid = ? AND leilao.estado = 0 " + /*" AND leilao.data > NOW() "*/
  691. "AND leilao.precomax > ? AND ? < (SELECT IFNULL(MIN(licitacao.quantia),leilao.precomax) FROM licitacao WHERE licitacao.leilaoid = ?) " +
  692. "FOR UPDATE;";
  693.  
  694. try {
  695. statement = connection.prepareStatement(query);
  696. statement.setLong(1, id);
  697. statement.setDouble(2, amount);
  698. statement.setDouble(3, amount);
  699. statement.setLong(4, id);
  700. ResultSet response = statement.executeQuery();
  701. aux = getArraylistLeiloes(response, connection);
  702. if (aux.size() != 1){
  703. System.out.println("size: "+aux.size());
  704. connection.commit();//por causa do FOR UPDATE
  705. return null;
  706. }
  707.  
  708. //connection.prepareStatement("LOCK TABLES licitacao AS l1 WRITE, licitacao AS l2 WRITE, licitacao WRITE;").execute();
  709.  
  710. query = "INSERT INTO licitacao (leilaoid, username, quantia) VALUES (?, ?, ?);";
  711. statement = connection.prepareStatement(query);
  712. statement.setLong(1, id);
  713. statement.setString(2, username);
  714. statement.setDouble(3, amount);
  715. statement.execute();
  716.  
  717. //connection.commit();
  718.  
  719. String licitacao = "SELECT l1.licitacaoid id, l1.username usernameSender, l1.quantia amount, l1.leilaoid leilaoId FROM licitacao l1 WHERE " +
  720. "l1.licitacaoid = (SELECT MAX(licitacaoid) FROM licitacao l2);";
  721. int bidId = 0, leilaoId = 0;
  722. String usernameSender="";
  723. try {
  724. statement = connection.prepareStatement(licitacao);
  725. response = statement.executeQuery();
  726. while(response.next()){
  727. bidId = response.getInt("id");
  728. usernameSender = response.getString("usernameSender");
  729. leilaoId = response.getInt("leilaoId");
  730. }
  731.  
  732. } catch (SQLException e) {
  733. System.out.println("Rollback");
  734. try {
  735. connection.rollback();
  736. } catch (SQLException e1) {
  737. System.out.println("Error doing rollback!");
  738. }
  739. e.printStackTrace();
  740. }
  741.  
  742.  
  743.  
  744. //connection.prepareStatement("UNLOCK TABLES;").execute();
  745. bidNotification(leilaoId, usernameSender, bidId, connection);
  746. connection.commit();
  747. return aux.get(0);
  748.  
  749. } catch (SQLException e) {
  750. System.out.println("Rollback");
  751. try {
  752. connection.rollback();
  753. } catch (SQLException e1) {
  754. System.out.println("Error doing rollback!");
  755. }
  756. e.printStackTrace();
  757. }
  758.  
  759. releaseConnection(c);
  760. return null;
  761. }
  762.  
  763.  
  764. public void bidNotification(int leilaoId, String usernameSender, int bidId, Connection connection) throws RemoteException {
  765. //DEVO USAR VIEWS E ESTAR SEMPRE A CRIAR E A ELIMINAR??
  766. //EXISTE GARANTIA QUE ISTO E CORRIDO A SEGUIR A FAZER A BID?? NO MAKE BID DEVIAMOS MANDAR NOTIFICACAO ANTES DE FAZER UNLOCK A TABLE
  767. PreparedStatement statement = null;
  768. String query = "CREATE VIEW lic_anteriores " +
  769. "AS " +
  770. "SELECT DISTINCT licitacao.username username FROM licitacao" +
  771. " WHERE licitacao.leilaoid = ? AND licitacao.username <> ?" +
  772. " GROUP BY licitacao.leilaoid, licitacao.username " +
  773. "UNION " +
  774. "SELECT user.username FROM user, leilao " +
  775. "WHERE user.username = leilao.username AND leilao.leilaoid = ?; ";
  776.  
  777.  
  778. try {
  779. statement = connection.prepareStatement(query);
  780. statement.setInt(1,leilaoId);
  781. statement.setString(2,usernameSender);
  782. statement.setInt(3,leilaoId);
  783. statement.execute();
  784.  
  785.  
  786. } catch (SQLException e) {
  787. System.out.println("Rollback");
  788. try {
  789. connection.rollback();
  790. } catch (SQLException e1) {
  791. System.out.println("Error doing rollback!");
  792. }
  793. e.printStackTrace();
  794. }
  795.  
  796. query = "INSERT INTO notificacao_licitacao (notificacaolicid, licitacaoid, username_receiver)" +
  797. " SELECT 0, ?, lic_anteriores.username FROM lic_anteriores;";
  798.  
  799. try {
  800. statement = connection.prepareStatement(query);
  801. statement.setInt(1,bidId);
  802. statement.execute();
  803. connection.commit();
  804. connection.prepareStatement("DROP VIEW lic_anteriores;").execute();
  805.  
  806. } catch (SQLException e) {
  807. System.out.println("Rollback");
  808. try {
  809. connection.rollback();
  810. } catch (SQLException e1) {
  811. System.out.println("Error doing rollback!");
  812. }
  813. e.printStackTrace();
  814. }
  815.  
  816. }
  817.  
  818.  
  819. public Leilao write_message(LinkedHashMap<String, String> data, String username) throws RemoteException {
  820. //if...e max()...??
  821.  
  822. int id = Integer.parseInt(data.get("id"));
  823. PreparedStatement statement = null;
  824. String text = data.get("text");
  825. ArrayList <Leilao> aux = new ArrayList<>();
  826.  
  827. dbConnection c = getConnection();
  828. Connection connection = c.connection;
  829.  
  830. String query = "SELECT * FROM leilao " +
  831. "WHERE leilao.leilaoid = ? AND leilao.estado = 0 FOR UPDATE";
  832.  
  833. try {
  834. statement = connection.prepareStatement(query);
  835. statement.setInt(1, id);
  836. ResultSet response = statement.executeQuery();
  837. /*System.out.println("Response: ");
  838. while(response.next())
  839. System.out.println(response.getString("leilaoid"));*/
  840.  
  841. aux = getArraylistLeiloes(response, connection);
  842. if(aux.size() != 1) {
  843. connection.commit();
  844. return null;
  845. }
  846.  
  847. } catch (SQLException e) {
  848. System.out.println("Rollback");
  849. try {
  850. connection.rollback();
  851. } catch (SQLException e1) {
  852. System.out.println("Error doing rollback!");
  853. }
  854. e.printStackTrace();
  855. }
  856.  
  857. try {
  858. query = "INSERT INTO mensagem (leilaoid, username, texto) VALUES (?, ?, ?);";
  859. statement = connection.prepareStatement(query);
  860. statement.setInt(1, id);
  861. statement.setString(2, username);
  862. statement.setString(3, text);
  863. statement.execute();
  864.  
  865. //connection.commit();
  866.  
  867. String msg = "SELECT mensagem.mensagemid id, mensagem.username usernameSender, mensagem.texto text, mensagem.leilaoid leilaoId FROM mensagem WHERE " +
  868. "mensagem.mensagemid= (SELECT MAX(mensagemid) FROM mensagem);";
  869. int msgId = 0, leilaoId = 0;
  870. String usernameSender="";
  871. statement = null;
  872. try {
  873. statement = connection.prepareStatement(msg);
  874. ResultSet response = statement.executeQuery();
  875. while(response.next()){
  876. msgId = response.getInt("id");
  877. usernameSender = response.getString("usernameSender");
  878. leilaoId = response.getInt("leilaoId");
  879. }
  880.  
  881.  
  882.  
  883. } catch (SQLException e) {
  884. e.printStackTrace();
  885. }
  886. msgNotification(leilaoId, usernameSender, msgId, connection);
  887. return aux.get(0);
  888.  
  889. } catch (SQLException e) {
  890. System.out.println("Rollback");
  891. try {
  892. connection.rollback();
  893. } catch (SQLException e1) {
  894. System.out.println("Error doing rollback!");
  895. }
  896. e.printStackTrace();
  897. }
  898.  
  899. releaseConnection(c);
  900. return null;
  901.  
  902. }
  903.  
  904.  
  905. public void msgNotification(int leilaoId, String usernameSender, int msgId, Connection connection) throws RemoteException {
  906.  
  907. PreparedStatement statement = null;
  908. String query = "CREATE VIEW user_anteriores " +
  909. "AS " +
  910. "SELECT licitacao.username username FROM licitacao " +
  911. "WHERE licitacao.leilaoid = ? AND licitacao.username <> ? " +
  912. "GROUP BY licitacao.leilaoid, licitacao.username " +
  913. "UNION " +
  914. "SELECT mensagem.username username FROM mensagem " +
  915. "WHERE mensagem.leilaoid = ? AND mensagem.username <> ? " +
  916. "GROUP BY mensagem.leilaoid, mensagem.username " +
  917. "UNION " +
  918. "SELECT user.username FROM user, leilao " +
  919. "WHERE user.username = leilao.username AND leilao.leilaoid = ?; ";
  920.  
  921.  
  922. try {
  923. statement = connection.prepareStatement(query);
  924. statement.setInt(1,leilaoId);
  925. statement.setString(2,usernameSender);
  926. statement.setInt(3,leilaoId);
  927. statement.setString(4,usernameSender);
  928. statement.setInt(5,leilaoId);
  929. statement.execute();
  930.  
  931.  
  932. } catch (SQLException e) {
  933. System.out.println("Rollback");
  934. try {
  935. connection.rollback();
  936. } catch (SQLException e1) {
  937. System.out.println("Error doing rollback!");
  938. }
  939. e.printStackTrace();
  940. }
  941.  
  942. query = "INSERT INTO notificacao_mensagem (notificacaomsgid, mensagemid, username_receiver)" +
  943. " SELECT 0, ?, user_anteriores.username FROM user_anteriores;";
  944.  
  945. try {
  946. statement = connection.prepareStatement(query);
  947. statement.setInt(1,msgId);
  948. statement.execute();
  949. connection.commit();
  950. connection.prepareStatement("DROP VIEW user_anteriores;").execute();
  951.  
  952. } catch (SQLException e) {
  953. System.out.println("Rollback");
  954. try {
  955. connection.rollback();
  956. } catch (SQLException e1) {
  957. System.out.println("Error doing rollback!");
  958. }
  959. e.printStackTrace();
  960. }
  961.  
  962.  
  963. }
  964.  
  965. public void checkBidNotf_clients() throws RemoteException{
  966. //QUE CONNECTION DEVEMOS USAR??
  967.  
  968. dbConnection c = getConnection();
  969. Connection connection = c.connection;
  970.  
  971. try {
  972. String query = "SELECT leilaoid idLeilao, lic.licitacaoid licitacaoId, lic.username username, lic.quantia amount, username_receiver userReceiver FROM notificacao_licitacao notf, licitacao lic " +
  973. "WHERE notf.licitacaoid = lic.licitacaoid AND username_receiver IN (SELECT user.username FROM user WHERE user.logado = true);";
  974.  
  975. PreparedStatement statement = connection.prepareStatement(query);
  976. ResultSet response = statement.executeQuery();
  977.  
  978. while(response.next()){
  979. String username = response.getString("username");
  980. String userReceiver = response.getString("userReceiver");
  981. Double quantia = response.getDouble("amount");
  982. int leilaoId = response.getInt("idLeilao");
  983. for (TCP_Interface s : tcpServers) {
  984. if(s.checkUser(userReceiver)) {
  985. s.sendMsg("notification_bid", userReceiver, String.valueOf(quantia), leilaoId, username);
  986. }
  987. }
  988. }
  989.  
  990. query = "DELETE FROM notificacao_licitacao WHERE username_receiver IN (SELECT user.username FROM user WHERE user.logado = true);";
  991.  
  992. statement = connection.prepareStatement(query);
  993. statement.execute();
  994. connection.commit();
  995.  
  996. } catch (SQLException e) {
  997. System.out.println("Rollback");
  998. try {
  999. connection.rollback();
  1000. } catch (SQLException e1) {
  1001. System.out.println("Error doing rollback!");
  1002. }
  1003. e.printStackTrace();
  1004. }
  1005. releaseConnection(c);
  1006.  
  1007. }
  1008.  
  1009. public void checkMsgNotf_clients() throws RemoteException{
  1010. //QUE CONNECTION DEVEMOS USAR??
  1011.  
  1012. dbConnection c = getConnection();
  1013. Connection connection = c.connection;
  1014.  
  1015. try {
  1016. String query = "SELECT msg.leilaoid idLeilao, msg.mensagemid mensagemId, msg.username username, msg.texto text, username_receiver userReceiver FROM notificacao_mensagem notf, mensagem msg " +
  1017. "WHERE notf.mensagemid = msg.mensagemid AND username_receiver IN (SELECT user.username FROM user WHERE user.logado = true);";
  1018.  
  1019. PreparedStatement statement = connection.prepareStatement(query);
  1020. ResultSet response = statement.executeQuery();
  1021.  
  1022. while(response.next()){
  1023. String username = response.getString("username");
  1024. String text = response.getString("text");
  1025. String userReceiver = response.getString("userReceiver");
  1026. int leilaoId = response.getInt("idLeilao");
  1027. for (TCP_Interface s : tcpServers) {
  1028. if(s.checkUser(userReceiver)) {
  1029. s.sendMsg("notification_message", userReceiver, text, leilaoId, username);
  1030. }
  1031. }
  1032. }
  1033.  
  1034. query = "DELETE FROM notificacao_mensagem WHERE username_receiver IN (SELECT user.username FROM user WHERE user.logado = true);";
  1035. statement = connection.prepareStatement(query);
  1036. statement.execute();
  1037. connection.commit();
  1038.  
  1039. } catch (SQLException e) {
  1040. System.out.println("Rollback");
  1041. try {
  1042. connection.rollback();
  1043. } catch (SQLException e1) {
  1044. System.out.println("Error doing rollback!");
  1045. }
  1046. e.printStackTrace();
  1047. }
  1048.  
  1049. releaseConnection(c);
  1050. }
  1051.  
  1052. // FicheirosObjetos
  1053.  
  1054. private synchronized static void importObjTCPServers(){
  1055. FicheiroDeObjeto file = new FicheiroDeObjeto();
  1056. try {
  1057. file.abreLeitura("iBei"+File.separator+"aux"+File.separator+"tcpServers.ser");
  1058. tcpServers = (List<TCP_Interface>) file.leObjeto();
  1059. file.fechaLeitura();
  1060. } catch (IOException e) {
  1061. System.out.println("File with TCPServers in users empty.");
  1062. } catch (ClassNotFoundException e1) {
  1063. System.out.println("Classe ArrayList/User not found.");
  1064. }
  1065. }
  1066.  
  1067. private synchronized void exportObjTCPServers() {
  1068. FicheiroDeObjeto file = new FicheiroDeObjeto();
  1069. try {
  1070. file.abreEscrita("iBei"+File.separator+"aux"+File.separator+"tcpServers.ser");
  1071. file.escreveObjeto(tcpServers);
  1072. file.fechaEscrita();
  1073. } catch (IOException e) {
  1074. e.printStackTrace();
  1075. }
  1076. }
  1077.  
  1078.  
  1079. private void verifica_terminoLeiloes(){
  1080.  
  1081. dbConnection c = getConnection();
  1082. Connection connection = c.connection;
  1083.  
  1084. //view auxiliar com o id e nome do atual vencedor de todos os leiloes
  1085. String aux = "CREATE VIEW aux " +
  1086. "AS " +
  1087. "SELECT licitacao.username nome, leilaoid leilaoid FROM licitacao " +
  1088. "WHERE (quantia, leilaoid) IN (SELECT MIN(quantia) minLic, leilaoid leilaoid FROM licitacao GROUP BY leilaoid);";
  1089.  
  1090. //view com nome e i id dos leiloes que acabaram
  1091. String user_vencedoresView ="CREATE VIEW user_vencedores " +
  1092. "AS " +
  1093. "SELECT leilao.leilaoid id, vencedores.nome nome FROM leilao, aux vencedores " +
  1094. "WHERE leilao.estado = 0 AND leilao.data < NOW() AND leilao.leilaoid = vencedores.leilaoid " +
  1095. "UNION " +
  1096. "SELECT leilao.leilaoid, null FROM leilao WHERE leilao.estado = 0 AND leilao.data < NOW() AND leilaoid NOT IN (SELECT licitacao.leilaoid FROM licitacao GROUP BY licitacao.leilaoid);";
  1097.  
  1098. try {
  1099.  
  1100. PreparedStatement statement = connection.prepareStatement(aux);
  1101. statement.execute();
  1102.  
  1103. statement = connection.prepareStatement(user_vencedoresView);
  1104. statement.execute();
  1105.  
  1106.  
  1107. String query = "SELECT * FROM user_vencedores;";
  1108.  
  1109. statement = connection.prepareStatement(query);
  1110. ResultSet response = statement.executeQuery();
  1111. while(response.next()){
  1112. int id = response.getInt("id");
  1113. String nome = response.getString("nome");
  1114. if(nome != null)
  1115. System.out.println("Winner of auction with id "+id+": "+nome);
  1116. else
  1117. System.out.println("Auction with id: "+id+" had no bids.");
  1118.  
  1119. }
  1120.  
  1121. query = "UPDATE user SET vitorias = vitorias + (SELECT COUNT(*) FROM user_vencedores WHERE nome = user.username);";
  1122. statement = connection.prepareStatement(query);
  1123. statement.execute();
  1124.  
  1125.  
  1126. query = "UPDATE leilao SET estado = 2 WHERE data < NOW();";
  1127. statement = connection.prepareStatement(query);
  1128. statement.execute();
  1129.  
  1130. connection.prepareStatement("DROP VIEW aux, user_vencedores;").execute();
  1131.  
  1132. connection.commit();
  1133.  
  1134. } catch (SQLException e) {
  1135. System.out.println("Rollback");
  1136. try {
  1137. connection.rollback();
  1138. } catch (SQLException e1) {
  1139. System.out.println("Error doing rollback!");
  1140. }
  1141. e.printStackTrace();
  1142. }
  1143.  
  1144. releaseConnection(c);
  1145. }
  1146.  
  1147. public User [] getArrayUsers(ResultSet response, Connection connection){
  1148.  
  1149. ArrayList <User> users = new ArrayList<>();
  1150.  
  1151. int i;
  1152. try {
  1153. while(response.next()) {
  1154. users.add(new User(response.getString("username"), "default"));
  1155. users.get(users.size()-1).setLeiloes(response.getInt("dados"));
  1156. users.get(users.size()-1).setvitorias(response.getInt("dados"));
  1157. }
  1158. User [] array = new User[users.size()];
  1159. for(i=0; i< array.length; i++){
  1160. array[i] = users.get(i);
  1161. }
  1162. return array;
  1163.  
  1164. } catch (SQLException e) {
  1165. System.out.println("Rollback");
  1166. try {
  1167. connection.rollback();
  1168. } catch (SQLException e1) {
  1169. System.out.println("Error doing rollback!");
  1170. }
  1171. e.printStackTrace();
  1172. }
  1173.  
  1174.  
  1175. return new User[0];
  1176. }
  1177.  
  1178. //ADMIN
  1179. public User [] statsVitorias() throws RemoteException{
  1180. //top
  1181.  
  1182. dbConnection c = getConnection();
  1183. Connection connection = c.connection;
  1184.  
  1185. User [] users = new User[10];
  1186. String query = "SELECT username, vitorias dados FROM user ORDER BY 2 ASC LIMIT 10;";
  1187. try {
  1188. PreparedStatement statement = connection.prepareStatement(query);
  1189. ResultSet response = statement.executeQuery();
  1190. users = getArrayUsers(response,connection);
  1191.  
  1192. } catch (SQLException e) {
  1193. System.out.println("Rollback");
  1194. try {
  1195. connection.rollback();
  1196. } catch (SQLException e1) {
  1197. System.out.println("Error doing rollback");
  1198. }
  1199. e.printStackTrace();
  1200. }
  1201.  
  1202. releaseConnection(c);
  1203. return users;
  1204.  
  1205. }
  1206.  
  1207. public User [] statsLeiloes() throws RemoteException{
  1208. //top 10
  1209.  
  1210. dbConnection c = getConnection();
  1211. Connection connection = c.connection;
  1212.  
  1213. User [] users = new User[10];
  1214. String queryLeiloes = "SELECT username, leiloes dados FROM user ORDER BY 2 ASC LIMIT 10;";
  1215. try {
  1216. PreparedStatement statement = connection.prepareStatement(queryLeiloes);
  1217. ResultSet resp = statement.executeQuery();
  1218. users = getArrayUsers(resp,connection);
  1219.  
  1220. } catch (SQLException e) {
  1221. System.out.println("Rollback");
  1222. try {
  1223. connection.rollback();
  1224. } catch (SQLException e1) {
  1225. System.out.println("Error doing rollback!");
  1226. }
  1227. e.printStackTrace();
  1228. }
  1229.  
  1230. releaseConnection(c);
  1231. return users;
  1232. }
  1233.  
  1234. public int statsLastWeek(){
  1235.  
  1236. dbConnection c = getConnection();
  1237. Connection connection = c.connection;
  1238.  
  1239. PreparedStatement statement = null;
  1240. String query = "SELECT COUNT(*) contador FROM leilao where data >= DATE_SUB(NOW(), INTERVAL 10 DAY);";
  1241.  
  1242. try {
  1243. statement = connection.prepareStatement(query);
  1244. ResultSet response = statement.executeQuery();
  1245. while(response.next()){
  1246. return response.getInt("contador");
  1247. }
  1248.  
  1249. connection.commit();
  1250.  
  1251. } catch (SQLException e) {
  1252. System.out.println("Rollback");
  1253. try {
  1254. connection.rollback();
  1255. } catch (SQLException e1) {
  1256. System.out.println("Error doing rollback!");
  1257. }
  1258. e.printStackTrace();
  1259.  
  1260.  
  1261. }
  1262. releaseConnection(c);
  1263. return 0;
  1264. }
  1265.  
  1266. public boolean cancelAuction (long id) throws RemoteException{
  1267. PreparedStatement statement = null;
  1268.  
  1269. dbConnection c = getConnection();
  1270. Connection connection = c.connection;
  1271.  
  1272. String query = "UPDATE leilao SET estado = 1 WHERE leilaoid = ?;";
  1273.  
  1274. try {
  1275. statement = connection.prepareStatement(query);
  1276. statement.setLong(1,id);
  1277. System.out.println(statement.execute());//return true or false
  1278.  
  1279. connection.commit();
  1280.  
  1281. } catch (SQLException e) {
  1282. System.out.println("Rollback");
  1283. try {
  1284. connection.rollback();
  1285. } catch (SQLException e1) {
  1286. System.out.println("Error doing rollback!");
  1287. }
  1288. e.printStackTrace();
  1289.  
  1290.  
  1291. }
  1292. releaseConnection(c);
  1293. return true;
  1294. }
  1295.  
  1296. public boolean banUser (String username) throws RemoteException{//remover a conta de user?
  1297.  
  1298. dbConnection c = getConnection();
  1299. Connection connection = c.connection;
  1300.  
  1301. PreparedStatement statement = null;
  1302. String ban_query="UPDATE user SET banido = true WHERE username = ?;";
  1303. String cancel_query="UPDATE leilao SET estado = 1 WHERE username = ? AND estado = 0;";
  1304. String msg_query="INSERT INTO mensagem (leilaoid,username,texto) SELECT licitacao.leilaoid, \"admin\" , \"Im sorry, the user "+username+" was banned\" FROM licitacao WHERE username = ? GROUP BY leilaoid;";
  1305.  
  1306. String bid_query = "UPDATE licitacao a SET quantia = (SELECT min(quantia) FROM (SELECT * FROM licitacao) b WHERE b.leilaoid = a.leilaoid AND b.username = ? ) " +
  1307. "WHERE a.quantia = (SELECT min(quantia) FROM (SELECT * FROM licitacao) d WHERE d.leilaoid = a.leilaoid) " +
  1308. "AND EXISTS(SELECT * FROM (SELECT * FROM licitacao) c WHERE c.leilaoid = a.leilaoid AND c.username = ? );";
  1309.  
  1310. String del_bid_user_query = "DELETE FROM licitacao WHERE username = ? AND leilaoid IN " +
  1311. "(SELECT leilaoid FROM leilao WHERE estado = 0);";
  1312.  
  1313.  
  1314.  
  1315. String del_bid_query = "DELETE a FROM licitacao a WHERE " +
  1316. "a.licitacaoid < ALL(SELECT b.licitacaoid FROM (SELECT * FROM licitacao) b WHERE b.quantia = (SELECT min(c.quantia) FROM (SELECT * FROM licitacao) c WHERE c.leilaoid=b.leilaoid)) " +
  1317. "AND a.quantia<=(SELECT min(d.quantia) FROM (SELECT * FROM licitacao) d WHERE d.leilaoid=a.leilaoid);";
  1318.  
  1319. try {
  1320. statement = connection.prepareStatement(ban_query);
  1321. statement.setString(1,username);
  1322. statement.execute();
  1323.  
  1324. statement = connection.prepareStatement(cancel_query);
  1325. statement.setString(1,username);
  1326. statement.execute();
  1327.  
  1328. statement = connection.prepareStatement(msg_query);
  1329. statement.setString(1,username);
  1330. statement.execute();
  1331.  
  1332.  
  1333. statement = connection.prepareStatement(bid_query);
  1334. statement.setString(1,username);
  1335. statement.setString(2,username);
  1336. statement.execute();
  1337.  
  1338. System.out.println("passou");
  1339. statement = connection.prepareStatement(del_bid_user_query);
  1340. statement.setString(1,username);
  1341. statement.execute();
  1342.  
  1343. statement = connection.prepareStatement(del_bid_query);
  1344. statement.execute();
  1345.  
  1346.  
  1347. connection.commit();
  1348.  
  1349. releaseConnection(c);
  1350.  
  1351. return true;
  1352.  
  1353. } catch (SQLException e) {
  1354. System.out.println("Rollback");
  1355. try {
  1356. connection.rollback();
  1357. } catch (SQLException e1) {
  1358. System.out.println("Error doing rollback!");
  1359. }
  1360. e.printStackTrace();
  1361. return false;
  1362. }
  1363.  
  1364.  
  1365. }
  1366.  
  1367.  
  1368. private static void start(){
  1369. try {
  1370. RMI_Server h = new RMI_Server();
  1371.  
  1372. Registry r = LocateRegistry.createRegistry(Integer.parseInt(primaryRmi[1]));
  1373. r.rebind("ibei", h);
  1374.  
  1375. System.out.println("RMI Server ready.");
  1376.  
  1377. //thread para verificar o termino dos leiloes
  1378.  
  1379. new Thread() {
  1380. public void run() {
  1381. while (true) {
  1382. try {
  1383. h.verifica_terminoLeiloes();
  1384. Thread.sleep(60000);
  1385. } catch (InterruptedException e) {
  1386. e.printStackTrace();
  1387. }
  1388. }
  1389. }
  1390. }.start();
  1391. } catch (RemoteException e) {
  1392. //e.printStackTrace();
  1393. }
  1394. }
  1395.  
  1396. public synchronized String teste() throws RemoteException {
  1397. return "Check primary RMI server";
  1398. }
  1399.  
  1400. private synchronized static void verifica(RMI_Interface h) {
  1401. try {
  1402. h= (RMI_Interface) LocateRegistry.getRegistry(primaryRmi[0], 7000).lookup("ibei");
  1403. String teste = h.teste();
  1404. System.out.println(teste);
  1405. try {
  1406. Thread.sleep(3000);
  1407. verifica(h);
  1408. } catch (InterruptedException e) {
  1409. e.printStackTrace();
  1410. }
  1411. } catch (RemoteException e){
  1412. if(count > 30) {
  1413. start();
  1414. /* importObjLogged();
  1415. importObjTCPServers();
  1416. System.out.println("[Base dados] Users loggados imported: " + loggados);
  1417. */ count = 0;
  1418. }
  1419. else{
  1420. try {
  1421. System.out.println("Waiting for Primary RMI be up again");
  1422. Thread.sleep(3000);
  1423. count += 3;
  1424. verifica(h);
  1425. } catch (InterruptedException e1) {
  1426. e1.printStackTrace();
  1427. }
  1428.  
  1429. }
  1430. } catch (NotBoundException e) {
  1431. e.printStackTrace();
  1432. }
  1433. }
  1434.  
  1435. public static void main(String args[]) {
  1436. if (args.length != 3 && args.length != 4) {
  1437. System.out.println("Usage: <Primary RMI Host> <RMI Port> <DB Host>");
  1438. System.out.println("Optional (Secondary RMI on other machine): ... <secondary RMI server ip> <secondary RMI port>");
  1439. System.exit(0);
  1440. } else if (args.length == 3) {
  1441. primaryRmi[0] = args[0];
  1442. primaryRmi[1] = args[1];
  1443. dbHost = args[2];
  1444. } else {
  1445. primaryRmi[0] = args[0];
  1446. primaryRmi[1] = args[1];
  1447. backupRmi[0] = args[2];
  1448. backupRmi[1] = args[3];
  1449. }
  1450.  
  1451. System.out.println("Establish connection with RMI Host: "+primaryRmi[0]);
  1452.  
  1453. try {
  1454. System.setProperty("java.rmi.server.hostname", primaryRmi[0]);
  1455. RMI_Interface h = (RMI_Interface) LocateRegistry.getRegistry(primaryRmi[0], Integer.parseInt(primaryRmi[1])).lookup("ibei");
  1456. verifica(h);
  1457. } catch (RemoteException | NotBoundException re) {
  1458. start();
  1459. }
  1460. }
  1461. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement