Advertisement
Guest User

RMIServer

a guest
Dec 8th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 44.52 KB | None | 0 0
  1. package rmiserver;
  2.  
  3. import java.rmi.*;
  4. import java.rmi.registry.LocateRegistry;
  5. import java.rmi.registry.Registry;
  6. import java.rmi.server.*;
  7. import java.security.MessageDigest;
  8. import java.net.*;
  9. import java.io.*;
  10. import java.math.BigDecimal;
  11. import java.math.BigInteger;
  12. import java.sql.*;
  13. import java.util.Date;
  14. import java.util.concurrent.TimeUnit;
  15. import java.util.logging.Level;
  16. import java.util.logging.Logger;
  17.  
  18. import java.util.HashMap;
  19.  
  20. import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
  21.  
  22. import java.text.DateFormat;
  23. import java.text.SimpleDateFormat;
  24. import java.util.*;
  25.  
  26. public class RMIServer extends UnicastRemoteObject implements RMIServerInterface {
  27.  
  28. // static TCPServerInterface client;
  29. static Connection myConn;
  30. static Connection myConn2;
  31. static TCPServerInterface client;
  32. static TCPServerInterface client2;
  33.  
  34. private static final long serialVersionUID = 20141107L;
  35. private HashMap<String, String> users;
  36.  
  37. public RMIServer() throws RemoteException {
  38. super();
  39. users = new HashMap<String, String>();
  40. users.put("bender", "rodriguez"); // static users and passwords, to
  41. // simplify the example
  42. users.put("fry", "philip");
  43. users.put("leela", "turanga");
  44. users.put("homer", "simpson");
  45.  
  46. }
  47.  
  48. public boolean userMatchesPassword(String user, String password) throws RemoteException {
  49. System.out.println("Looking up " + user + "...");
  50. return users.containsKey(user) && users.get(user).equals(password);
  51. }
  52.  
  53. /**
  54. * returns all the user names
  55. */
  56. public ArrayList<String> getAllUsers() {
  57. System.out.println("Looking up all users...");
  58. return new ArrayList<String>(users.keySet());
  59. }
  60.  
  61. public void subscribe(TCPServerInterface c, int i) throws RemoteException {
  62. if (i == 1) {
  63. client = c;
  64. } else {
  65. client2 = c;
  66. }
  67. }
  68.  
  69. // M�todos do servidor RMI que o servidor TCP pode usar;
  70. // REGISTAR CONTA
  71. public String register(String username, String password) throws RemoteException {
  72. int check = 0;
  73. String resultado;
  74. // -------------------------------------
  75. // Verificar se o registo pode ser feito;
  76. // -------------------------------------
  77. Statement myStmt;
  78.  
  79. // PreparedStatement Qusername;
  80. // PreparedStatement Qpassword;
  81. //
  82. // String FindUsername = "SELECT USERNAME\n" + "FROM users\n" + "WHERE
  83. // USERNAME = ?";
  84. // String Findpassword = "INSERT INTO users (USERNAME, PASSWORD, ONLINE,
  85. // USER_STATE)\n " + "VALUES (?, ?, 0, 'active')";
  86. try {
  87.  
  88. myStmt = myConn.createStatement();
  89.  
  90. myConn.setAutoCommit(false);
  91.  
  92. ResultSet myRs = myStmt
  93. .executeQuery("SELECT USERNAME\n" + "FROM users\n" + "WHERE USERNAME ='" + username + "'");// results
  94. // set
  95.  
  96. if (myRs.next()) {
  97.  
  98. if (myRs.getString("USERNAME").equals(username)) {
  99. check = 1;
  100.  
  101. }
  102. } else if (check == 0) {
  103. String sql = "INSERT INTO users (USERNAME, PASSWORD, ONLINE, USER_STATE)\n " + "VALUES ('" + username
  104. + "', '" + encryptPassword(password) + "', 0, 'active')";
  105. myStmt.executeUpdate(sql); // results set
  106. }
  107. // myRs.close();
  108. // myStmt.close();
  109. myConn.commit();
  110. } catch (SQLException e) {// tratar exception de limite de carateres
  111. check = 1;
  112. try {
  113. System.out.println("Transaction in register is being rolled back");
  114. myConn.rollback();
  115. } catch (SQLException e1) {
  116. // TODO Auto-generated catch block
  117. e1.printStackTrace();
  118. }
  119. }
  120.  
  121. if (check == 0) {
  122.  
  123. resultado = "type: register, ok: true";
  124.  
  125. } else {
  126.  
  127. resultado = "type: register, ok: false";
  128. }
  129. return resultado;
  130. }
  131.  
  132. // FAZER LOGIN
  133. public String login(String username, String password) throws RemoteException {
  134.  
  135. int check = 0;
  136. String resultado;
  137. // -----------------------------------
  138. // Verificar se o login pode ser feito
  139. // -----------------------------------
  140. Statement myStmt;
  141. try {
  142.  
  143. myStmt = myConn.createStatement();
  144. myConn.setAutoCommit(false);
  145.  
  146. ResultSet myRs = myStmt.executeQuery("SELECT USERNAME, PASSWORD\n" + "FROM users\n" + "WHERE USERNAME ='"
  147. + username + "' AND PASSWORD = '" + encryptPassword(password) + "'");// results
  148. // set
  149.  
  150. if (myRs.next()) {
  151.  
  152. check = 0;
  153. String sql = "UPDATE users\n " + "SET ONLINE = 1\n" + "WHERE USERNAME ='" + username
  154. + "' AND PASSWORD = '" + encryptPassword(password) + "' ";
  155. myStmt.executeUpdate(sql); // results set
  156.  
  157. } else {
  158. check = 1;
  159.  
  160. }
  161. myConn.commit();
  162.  
  163. } catch (SQLException e) {
  164. check = 1;
  165. try {
  166. System.out.println("Transaction in login is being rolled back");
  167. myConn.rollback();
  168. } catch (SQLException e1) {
  169. // TODO Auto-generated catch block
  170. e1.printStackTrace();
  171. }
  172. }
  173.  
  174. if (check == 0) {
  175.  
  176. resultado = "type: login, ok: true";
  177. } else {
  178. resultado = "type: login, ok: false";
  179. }
  180. return resultado;
  181.  
  182. }
  183.  
  184. // LOGOUT
  185. public void logout(String username) throws RemoteException {
  186.  
  187. // -----------------------------------
  188. // LOGOUT
  189. // -----------------------------------
  190. Statement myStmt;
  191. try {
  192. myConn.setAutoCommit(false);
  193. myStmt = myConn.createStatement();
  194.  
  195. String sql = "UPDATE users\n " + "SET ONLINE = 0\n" + "WHERE USERNAME ='" + username + "'";
  196. myStmt.executeUpdate(sql); // results set
  197. myConn.commit();
  198. } catch (SQLException e) {
  199. try {
  200. System.out.println("Transaction in logout is being rolled back");
  201. myConn.rollback();
  202. } catch (SQLException e1) {
  203. // TODO Auto-generated catch block
  204. e1.printStackTrace();
  205. }
  206. }
  207.  
  208. }
  209.  
  210. public boolean isloggedin(String username) throws RemoteException {
  211.  
  212. Statement myStmt;
  213. try {
  214.  
  215. myStmt = myConn.createStatement();
  216.  
  217. ResultSet myRs = myStmt.executeQuery("SELECT USERNAME\n" + "FROM users\n" + "WHERE USERNAME ='" + username
  218. + "' AND ONLINE = 1 AND USER_STATE = 'active'");// results
  219. // set
  220.  
  221. if (myRs.next()) {
  222. return true;
  223. }
  224. } catch (SQLException e) {// tratar exception de limite de carateres
  225. System.out.println("Error in function isloggedin");
  226. e.printStackTrace();
  227. }
  228. return false;
  229. }
  230.  
  231. // CRIAR LEIL�O
  232. public String create_auction(long code, String title, String description, String Date, int amount, String username)
  233. throws RemoteException {
  234. // type: login, username: imota, password: cenasmalucas3
  235. // type: create_auction, code: 9780451524935, title: 1984, description:
  236. // big brother i s watching you, deadline: 2017-01-01 00:01, amount: 10
  237.  
  238. int check = 0;
  239. String resultado;
  240. // -------------------------------------
  241. // Verificar se o registo pode ser feito;
  242. // -------------------------------------
  243.  
  244. Statement myStmt;
  245. try {
  246.  
  247. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  248. Date date2 = format.parse(getcurrentdate());
  249. Date date = format.parse(Date);
  250. if ((date.compareTo(date2) < 0) || amount <= 0) {
  251. return "type: create_auction, ok: false";
  252. }
  253.  
  254. myStmt = myConn.createStatement();
  255. myConn.setAutoCommit(false);
  256.  
  257. ResultSet myRs = myStmt
  258. .executeQuery("SELECT ID_USERS\n" + "FROM users\n" + "WHERE USERNAME ='" + username + "'");// results
  259. // set
  260.  
  261. if (myRs.next()) {
  262. int id_user = myRs.getInt("ID_USERS");
  263.  
  264. String commandSql = "INSERT INTO auction (CODE, TITLE, DESCRIPTION, DEADLINE, ID_USER, AUCTION_STATE)\n"
  265. + "values (" + code + ", '" + title + "', '" + description + "', '" + Date + "', " + id_user
  266. + ", 'active')";
  267. myStmt.executeUpdate(commandSql); // results set
  268.  
  269. // para a bid, preciso de saber o ID_AUCTION
  270. ResultSet myRs2 = myStmt.executeQuery("SELECT ID_AUCTION " + "FROM auction " + "WHERE (CODE =" + code
  271. + " AND TITLE='" + title + "' AND DESCRIPTION='" + description + "' AND DEADLINE='" + Date
  272. + "' AND ID_USER=" + id_user + " AND AUCTION_STATE='active')");
  273. // myRs2.next();
  274. myRs2.last();
  275.  
  276. // adiciona ao array das deadlines a data final da auction
  277. client.writetodeadlinearray(myRs2.getInt("ID_AUCTION"), Date);
  278.  
  279. // acrescento a tabela de bids
  280. String commandSql2 = "INSERT INTO bids (AMOUNT, ID_AUCTION, ID_USER, BID_STATE)\n" + "values (" + amount
  281. + ", " + myRs2.getInt("ID_AUCTION") + ", " + id_user + ", 'active')";
  282. myStmt.executeUpdate(commandSql2);
  283. check = 1;
  284. myConn.commit();
  285. }
  286.  
  287. } catch (SQLException e) {// tratar exception de limite de carateres
  288. check = 0;
  289. try {
  290. System.out.println("Transaction of create auction is being rolled back");
  291. myConn.rollback();
  292. } catch (SQLException e1) {
  293. // TODO Auto-generated catch block
  294. e1.printStackTrace();
  295. }
  296. } catch (java.text.ParseException ex) {
  297. Logger.getLogger(RMIServer.class.getName()).log(Level.SEVERE, null, ex);
  298. }
  299. // -----------------------------------
  300. // Verificar se o leil�o foi criado
  301. // -----------------------------------
  302. if (check == 1) {
  303. resultado = "type: create_auction, ok: true";
  304. } else {
  305. resultado = "type: create_auction, ok: false";
  306. }
  307. return resultado;
  308.  
  309. }
  310.  
  311. // PESQUISAR POR LEIL�O
  312. public String search_auction(long code) throws RemoteException {
  313. // é o code do artigo
  314.  
  315. int check = 0;
  316. String resultado;
  317. String concat = "";
  318. int tem_alguma = 0;
  319. int i = 0;
  320. Statement myStmt;
  321. try {
  322. myStmt = myConn.createStatement();
  323.  
  324. ResultSet myRs = myStmt.executeQuery(
  325. "SELECT ID_AUCTION, CODE, TITLE\n" + "FROM auction\n" + "WHERE CODE =" + BigInteger.valueOf(code));// results
  326. // set
  327.  
  328. while (myRs.next()) {
  329. concat += ", items_" + i + "_id: " + myRs.getInt("ID_AUCTION") + ", items_" + i + "_code: "
  330. + myRs.getBigDecimal("CODE") + ", title: " + myRs.getString("TITLE");
  331. i++;
  332. tem_alguma = 1;
  333. }
  334.  
  335. // concat += ", items_" + i + "_id: " + myRs.getInt("ID_AUCTION") +
  336. // ", items_" + i + "_code: " + myRs.getBigDecimal("CODE") + ",
  337. // title: " + myRs.getString("TITLE");
  338. check = 1;
  339. myRs.close();
  340. } catch (SQLException e) {
  341. check = 0;
  342. e.printStackTrace();
  343. }
  344.  
  345. if (check == 1) {
  346. if (tem_alguma == 1) {
  347. resultado = "type: search_auction, items_count: " + (i) + concat;
  348. } else {
  349. resultado = "type: search_auction, items_count: " + (i);
  350. }
  351.  
  352. } else {
  353. resultado = "type: search_auction, ok: false";
  354. }
  355. return resultado;
  356. }
  357.  
  358. // CONSULTAR DETALHES DE LEIL�O
  359. public String detail_auction(int id) throws RemoteException {
  360.  
  361. String resultado = "";
  362. // -----------------------------------
  363. // Verificar detalhes de leil�o
  364. // -----------------------------------
  365. Statement myStmt;
  366. ResultSet myRs;
  367. String messages = "";
  368. int i = 0;
  369. // Calendar cal =Calendar.getInstance();
  370.  
  371. try {
  372. myStmt = myConn.createStatement();
  373. myRs = myStmt.executeQuery(
  374. "SELECT TITLE, DESCRIPTION, DEADLINE\n" + "FROM auction\n" + "WHERE ID_AUCTION = " + id);
  375. myRs.next();
  376. resultado = "type: detail_auction, title: " + myRs.getString("TITLE") + ", description: "
  377. + myRs.getString("DESCRIPTION") + ", deadline: "
  378. + myRs.getTimestamp("DEADLINE").toString().substring(0, 19);
  379.  
  380. // myRs.close();
  381. // myStmt.close();
  382.  
  383. ResultSet myRs2;
  384. Statement myStmt2;
  385. myStmt2 = myConn.createStatement();
  386. myRs2 = myStmt2.executeQuery("SELECT ID_USER, TEXT\n" + "FROM messages\n" + "WHERE ID_AUCTION = " + id);
  387. // myStmt.close();
  388.  
  389. while (myRs2.next()) {
  390. messages += ", message_" + i + "_user: " + getusername(myRs2.getInt("ID_USER")) + ", message_" + i
  391. + "_text: " + myRs2.getString("TEXT");
  392. i++;
  393. }
  394. resultado += ", messages_count: " + i;
  395.  
  396. resultado += messages;
  397.  
  398. ResultSet myRs3;
  399. Statement myStmt3;
  400. myStmt3 = myConn.createStatement();
  401. myRs3 = myStmt3
  402. .executeQuery("SELECT COUNT(AMOUNT) AS BIDS_COUNT\n" + "FROM bids\n" + "WHERE ID_AUCTION = " + id);
  403. myRs3.next();
  404. resultado += ", bids_count: " + myRs3.getInt("BIDS_COUNT");
  405. // myStmt.close();
  406.  
  407. } catch (SQLException e) {
  408.  
  409. e.printStackTrace();
  410. }
  411.  
  412. return resultado;
  413. }
  414.  
  415. public int getuserid(String username) {
  416.  
  417. int id;
  418.  
  419. Statement myStmt;
  420. try {
  421. myStmt = myConn.createStatement();
  422. ResultSet myRs = myStmt
  423. .executeQuery("SELECT ID_USERS\n" + "FROM users\n" + "WHERE USERNAME = '" + username + "'");
  424. myRs.next();
  425. id = myRs.getInt("ID_USERS");
  426. return id;
  427. } catch (SQLException e) {
  428.  
  429. e.printStackTrace();
  430. }
  431.  
  432. return -1;
  433.  
  434. }
  435.  
  436. public String getcurrentdate() {
  437.  
  438. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  439. // get current date time with Date()
  440. Date date = new Date();
  441. return dateFormat.format(date);
  442. }
  443.  
  444. public String getpreviousmessageowner(int id_auction, int userid) {
  445. String resposta = "";
  446.  
  447. Statement myStmt;
  448. ResultSet myRs;
  449. try {
  450. myStmt = myConn.createStatement();
  451. myRs = myStmt.executeQuery("SELECT DISTINCT ID_USER\n" + "FROM messages\n" + "WHERE ID_AUCTION = "
  452. + id_auction + " AND NOT ID_USER = " + userid);// results
  453. // set
  454.  
  455. while (myRs.next()) {
  456.  
  457. resposta += myRs.getInt("ID_USER") + "_";
  458.  
  459. }
  460. } catch (SQLException e) {
  461.  
  462. e.printStackTrace();
  463. }
  464.  
  465. return resposta;
  466. }
  467.  
  468. // GET USERNAME FROM USER ID
  469. public String getusername(int id) throws RemoteException {
  470. String username;
  471.  
  472. Statement myStmt;
  473. try {
  474. myStmt = myConn.createStatement();
  475. ResultSet myRs = myStmt.executeQuery("SELECT USERNAME\n" + "FROM users\n" + "WHERE ID_USERS = " + id);
  476. myRs.next();
  477. username = myRs.getString("USERNAME");
  478. return username;
  479. } catch (SQLException e) {
  480.  
  481. e.printStackTrace();
  482. }
  483.  
  484. return "";
  485.  
  486. }
  487.  
  488. public void sendmessagenotification() throws RemoteException {
  489.  
  490. Statement myStmt;
  491. ResultSet myRs;
  492. String sendto;
  493. int auction_id;
  494. String text;
  495. int sender_id;
  496. int msg_id;
  497.  
  498. try {
  499.  
  500. myStmt = myConn.createStatement();
  501. myConn.setAutoCommit(false);
  502. myRs = myStmt.executeQuery("SELECT ID_AUCTION, ID_MSG, TEXT, ID_USER, SENDTO\n" + "FROM messages\n");
  503. while (myRs.next()) {
  504.  
  505. String[] sendto_parsed;
  506. ArrayList<String> sendto_final = new ArrayList<>();
  507. String offline = "";
  508.  
  509. auction_id = myRs.getInt("ID_AUCTION");
  510. text = myRs.getString("TEXT");
  511. sender_id = myRs.getInt("ID_USER");
  512. msg_id = myRs.getInt("ID_MSG");
  513.  
  514. sendto = myRs.getString("SENDTO");
  515. if (!sendto.equals("")) {
  516. sendto_parsed = sendto.split("_");
  517. sendto_final.addAll(Arrays.asList(sendto_parsed));
  518.  
  519. for (int i = 0; i < sendto_final.size(); i++) {
  520.  
  521. String aux;
  522.  
  523. aux = getusername(Integer.parseInt(sendto_final.get(i)));
  524.  
  525. if (isloggedin(aux)) {
  526.  
  527. try {
  528.  
  529. client.message_notification(auction_id, getusername(sender_id), aux, text);
  530. } catch (Exception e) {
  531.  
  532. }
  533. try {
  534.  
  535. client2.message_notification(auction_id, getusername(sender_id), aux, text);
  536. } catch (Exception e) {
  537.  
  538. }
  539. } else {
  540.  
  541. offline += sendto_final.get(i) + "_";
  542.  
  543. }
  544. }
  545. String sql = "UPDATE messages\n " + "SET SENDTO = '" + offline + "'\n" + "WHERE ID_MSG = " + msg_id;
  546. myStmt.executeUpdate(sql);
  547. myConn.commit();
  548. }
  549. }
  550. myRs.close();
  551. myStmt.close();
  552. } catch (SQLException e) {
  553. try {
  554. System.out.println("Transaction of send message notification is being rolled back");
  555. myConn.rollback();
  556. } catch (SQLException e1) {
  557. // TODO Auto-generated catch block
  558. e1.printStackTrace();
  559. }
  560. }
  561.  
  562. }
  563.  
  564. public String message(int id, String text, String username) throws RemoteException {
  565. // type: message, id: 1, text: alguma editora em especial?
  566. // type: login, username: codfish, password: cenasmalucas
  567. // type: login, username: asilva, password: cenasmalucas2
  568. // type: login, username: imota, password: cenasmalucas3
  569.  
  570. int userid = 0;
  571. String resultado;
  572. String date;
  573. String sendto;
  574.  
  575. // -----------------------------------
  576. // Verificar se foi colocada uma mensagem no mural do leil�o
  577. // -----------------------------------
  578.  
  579. Statement myStmt;
  580. userid = getuserid(username);
  581. date = getcurrentdate();
  582. sendto = getpreviousmessageowner(id, userid);
  583.  
  584. try {
  585.  
  586. myStmt = myConn.createStatement();
  587. myConn.setAutoCommit(false);
  588. // ResultSet myRs;
  589.  
  590. String sql = "INSERT INTO messages (ID_AUCTION, TEXT, ID_USER, DATE, SENDTO)\n " + "VALUES (" + id + ", '"
  591. + text + "', " + userid + ", '" + date + "', '" + sendto + "')";
  592. myStmt.executeUpdate(sql); // results set
  593. myStmt.close();
  594. myConn.commit();
  595.  
  596. } catch (SQLException e) {
  597. resultado = "type: message, ok: false";
  598. try {
  599. System.out.println("Transaction of insert message is being rolled back");
  600. myConn.rollback();
  601. } catch (SQLException e1) {
  602. // TODO Auto-generated catch block
  603. e1.printStackTrace();
  604. }
  605.  
  606. return resultado;
  607. }
  608.  
  609. resultado = "type: message, ok: true";
  610.  
  611. if (!username.equals("admin")) {
  612. try {
  613. client.message_notification(id, username, username, text);
  614.  
  615. } catch (Exception e) {
  616.  
  617. }
  618. try {
  619. client2.message_notification(id, username, username, text);
  620. } catch (Exception e) {
  621. e.printStackTrace();
  622. }
  623. }
  624.  
  625. sendmessagenotification();
  626.  
  627. return resultado;
  628.  
  629. }
  630.  
  631. public String edit_auction(int id, String edit, String edit_field, String username) throws RemoteException {
  632.  
  633. String resultado = "";
  634. Statement myStmt;
  635. int check = 0;
  636. int type = 0;
  637.  
  638. try {
  639.  
  640. if (edit.toUpperCase().equals("DEADLINE")) {
  641. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  642. Date date2 = format.parse(getcurrentdate());
  643. Date date = format.parse(edit_field);
  644. if (date.compareTo(date2) < 0) {
  645. return "type: edit_auction, ok: false";
  646. }
  647. type = 3;
  648. } else if (edit.toUpperCase().equals("DESCRIPTION")) {
  649. type = 2;
  650.  
  651. } else if (edit.toUpperCase().equals("TITLE")) {
  652. type = 1;
  653. }
  654.  
  655. int idUser = getuserid(username);
  656.  
  657. ResultSet myRs;
  658. Statement myStmt2;
  659.  
  660. myStmt2 = myConn.createStatement();
  661. myConn.setAutoCommit(false);
  662.  
  663. myRs = myStmt2.executeQuery("SELECT ID_USER FROM auction WHERE ID_AUCTION = " + id);
  664. myRs.next();
  665.  
  666. if (myRs.getInt("ID_USER") != idUser) {
  667. return "type: edit_auction, ok: false";
  668. }
  669.  
  670. myRs = myStmt2.executeQuery(
  671. "SELECT " + edit.toUpperCase() + "\n" + "FROM auction\n" + "WHERE ID_AUCTION = " + id);
  672. myRs.next();
  673. // myStmt2.close();
  674.  
  675. Statement myStmt3;
  676. myStmt3 = myConn.createStatement();
  677. String commandSql4 = "INSERT INTO historico (ID_AUCTION, TYPE, EDIT)\n" + "values (" + id + ", " + type
  678. + ", '" + myRs.getString(edit.toUpperCase()) + "')";
  679. myStmt3.executeUpdate(commandSql4);
  680. // myStmt3.close();
  681.  
  682. myStmt = myConn.createStatement();
  683. String sql = "UPDATE auction\n " + "SET " + edit.toUpperCase() + " = '" + edit_field + "'\n"
  684. + "WHERE ID_AUCTION = " + id;
  685. myStmt.executeUpdate(sql); // results set
  686. // myStmt.close();
  687.  
  688. myConn.commit();
  689.  
  690. } catch (SQLException e) {
  691. check = 1;
  692. try {
  693. System.out.println("Transaction of edit_auction is being rolled back");
  694. myConn.rollback();
  695. } catch (SQLException e1) {
  696. // TODO Auto-generated catch block
  697. e1.printStackTrace();
  698. }
  699. } catch (java.text.ParseException ex) {
  700. Logger.getLogger(RMIServer.class.getName()).log(Level.SEVERE, null, ex);
  701. }
  702. if (check == 0) {
  703.  
  704. resultado = "type: edit_auction, ok: true";
  705.  
  706. /*
  707. * ResultSet myRs; try { myStmt = myConn.createStatement(); myRs =
  708. * myStmt.executeQuery("SELECT *\n" + "FROM auction\n" +
  709. * "WHERE ID_AUCTION = " + id); myRs.next();
  710. *
  711. * String commandSql4 =
  712. * "INSERT INTO historico (CODE, TITLE, DESCRIPTION, DEADLINE, AMOUNT, BIDS_COUNT, ID_USER, ID_AUCTION, AUCTION_STATE)\n"
  713. * + "values (" + myRs.getBigDecimal("CODE") + ", '" +
  714. * myRs.getString("TITLE") + "', '" + myRs.getString("DESCRIPTION")
  715. * + "', '" + myRs.getString("DEADLINE") + "', " +
  716. * myRs.getInt("AMOUNT") + ", " + myRs.getInt("BIDS_COUNT") + ", " +
  717. * myRs.getInt("ID_USER") + ", " + myRs.getInt("ID_AUCTION") + ", '"
  718. * + myRs.getString("AUCTION_STATE") + "')";
  719. * myStmt.executeUpdate(commandSql4);
  720. *
  721. * } catch (SQLException e) {
  722. *
  723. * e.printStackTrace(); }
  724. */
  725.  
  726. } else {
  727. resultado = "type: edit_auction, ok: false";
  728. }
  729.  
  730. return resultado;
  731. }
  732.  
  733. public String encryptPassword(String base) {
  734. try {
  735. MessageDigest digest = MessageDigest.getInstance("SHA-256");
  736. byte[] hash = digest.digest(base.getBytes("UTF-8"));
  737. StringBuffer hexString = new StringBuffer();
  738.  
  739. for (int i = 0; i < hash.length; i++) {
  740. String hex = Integer.toHexString(0xff & hash[i]);
  741. if (hex.length() == 1)
  742. hexString.append('0');
  743. hexString.append(hex);
  744. }
  745.  
  746. return hexString.toString();
  747. } catch (Exception ex) {
  748. throw new RuntimeException(ex);
  749. }
  750. }
  751.  
  752. // CONSULTAR TODOS OS LEIL�ES EM QUE O UTILIZADOR TENHA ATIVIDADE
  753. public String my_auctions(String username) throws RemoteException {
  754.  
  755. int check = 0;
  756. String resultado;
  757. // -----------------------------------
  758. // Verifico se username pode ser repetido ou nao?
  759. // -----------------------------------
  760. String concat = "";
  761. int i = 0;
  762. int tem_alguma = 0;
  763. int id_user;
  764. Statement myStmt;
  765. // Statement myStmt2;
  766. try {
  767. myStmt = myConn.createStatement();
  768.  
  769. // myStmt2 = myConn2.createStatement();
  770.  
  771. ResultSet myRs = myStmt.executeQuery(
  772. "SELECT USERNAME, ID_USERS\n" + "FROM users\n" + "WHERE USERNAME = '" + username + "'");// results
  773. // set
  774.  
  775. myRs.next();
  776. id_user = myRs.getInt("ID_USERS");
  777. myRs.close();
  778.  
  779. // get bids do utilizador
  780. // ResultSet myRs3 = myStmt2.executeQuery("SELECT DISTINCT
  781. // ID_AUCTION\n"
  782. // + "FROM bids\n"
  783. // + "WHERE ID_USER =" + id_user +"AND ID_AUCTION IN SELECT DISTINCT
  784. // ID_AUCTION, CODE,);
  785. //
  786. //
  787. // get leiloes do utilizador
  788. ResultSet myRs2 = myStmt.executeQuery("SELECT DISTINCT ID_AUCTION, CODE, TITLE, ID_USER, AUCTION_STATE\n"
  789. + "FROM auction\n" + "WHERE (ID_USER = " + id_user
  790. + " OR ID_AUCTION IN (SELECT DISTINCT ID_AUCTION FROM bids WHERE ID_USER = " + id_user + "))");
  791.  
  792. // edit cima!
  793. while (myRs2.next()) {
  794.  
  795. concat += ", items_" + i + "_id: " + myRs2.getInt("ID_AUCTION") + ", items_" + i + "_code: "
  796. + myRs2.getBigDecimal("CODE") + ", title: " + myRs2.getString("TITLE");
  797. i++;
  798. tem_alguma = 1;
  799. }
  800.  
  801. // concat += ", items_" + i + "_id: " + myRs2.getInt("ID_AUCTION") +
  802. // ", items_" + i + "_code: " + myRs2.getBigDecimal("CODE") + ",
  803. // title: " + myRs2.getString("TITLE");
  804. myRs2.close();
  805.  
  806. check = 1;
  807. myRs2.close();
  808. } catch (SQLException e) {
  809. check = 0;
  810. e.printStackTrace();
  811. }
  812.  
  813. if (check == 1) {
  814. if (tem_alguma == 1) {
  815. resultado = "type: my_auctions, items_count: " + (i) + concat;
  816. } else {
  817. resultado = "type: my_auctions, items_count: " + (i);
  818. }
  819.  
  820. } else {
  821. resultado = "type: my_auctions, ok: false";
  822. }
  823. return resultado;
  824.  
  825. }
  826.  
  827. public boolean isTerminated(int id_auction) {
  828. Statement myStmt;
  829. try {
  830. myStmt = myConn.createStatement();
  831. ResultSet myRs = myStmt
  832. .executeQuery("SELECT AUCTION_STATE\n" + "FROM auction\n" + "WHERE ID_AUCTION = " + id_auction);// results
  833. // set
  834. myRs.next();
  835. if (myRs.getString("AUCTION_STATE").equals("terminated")) {
  836. return true;
  837. }
  838. } catch (SQLException ex) {
  839. Logger.getLogger(RMIServer.class.getName()).log(Level.SEVERE, null, ex);
  840. }
  841.  
  842. return false;
  843. }
  844.  
  845. // EFETUAR UMA LICITA��O NUM LEIL�O
  846. public String bid(int id, int amount, String username) throws RemoteException, java.text.ParseException {
  847.  
  848. int check = 0;
  849. String resultado = "";
  850. Date date;
  851. int aux_id_alteracao = 0;
  852. int aux_amount = 0;
  853. int aux = 0;
  854. int id_user = 0;
  855. // -----------------------------------
  856. // Verifico se username pode ser repetido ou nao?
  857. // -----------------------------------
  858. String concat = "";
  859. int i = 0;
  860. Statement myStmt;
  861. Statement myStmt2;
  862. ResultSet myRs4;
  863. int val_bids_count;
  864.  
  865. if ((isCancelled(id) == 0) && !isTerminated(id) && isloggedin(username)) {
  866.  
  867. try {
  868. myStmt = myConn.createStatement();
  869. myStmt2 = myConn2.createStatement();
  870. myConn.setAutoCommit(false);
  871. // myConn2.setAutoCommit(false);
  872. // dá-me o valor(amount) atual do leilao
  873. ResultSet myRs = myStmt2.executeQuery("SELECT MIN(bids.AMOUNT) AS min_amount, auction.DEADLINE\n"
  874. + "FROM bids, auction\n" + "WHERE auction.ID_AUCTION = " + id
  875. + " AND bids.ID_AUCTION = auction.ID_AUCTION AND (NOT(bids.BID_STATE = 'cancelled'))");// results
  876. // set
  877.  
  878. // preciso do ID_user
  879. ResultSet myRs2 = myStmt
  880. .executeQuery("SELECT ID_USERS\n" + "FROM users\n" + "WHERE USERNAME = '" + username + "'");// results
  881. // set
  882.  
  883. myRs2.next();
  884. id_user = myRs2.getInt("ID_USERS");
  885.  
  886. // myRs2 = myStmt.executeQuery("SELECT ID_ALTERACAO, AMOUNT\n"
  887. // + "FROM historico\n"
  888. // + "WHERE ID_AUCTION = " + id);
  889. //
  890. // while (myRs2.next()) {
  891. // if (aux == 0) {
  892. // aux_id_alteracao = myRs2.getInt("ID_ALTERACAO");
  893. // aux_amount_inicial = myRs2.getInt("AMOUNT");
  894. // aux++;
  895. // } else if (myRs2.getInt("ID_ALTERACAO") < aux_id_alteracao) {
  896. // aux_id_alteracao = myRs2.getInt("ID_ALTERACAO");
  897. // aux_amount_inicial = myRs2.getInt("AMOUNT");
  898. // }
  899. // }
  900. // myRs2.close();
  901. if (isBanned(id_user) == 1) {
  902. System.out.println("User banido");
  903. return "type: bid, ok: false";
  904. }
  905. // aux_amount=myRs.getInt("min_amount");
  906. //
  907. // if (amount > aux_amount) {
  908. // System.out.println("quantia da licitacao maior que quantia
  909. // minima");
  910. // return "type: bid, ok: false";
  911. // }
  912. //
  913.  
  914. System.out.println("next");
  915. myRs.next();
  916. if ((amount < myRs.getInt("min_amount"))|| amount>=0) {// so aceita valores
  917. // menores que
  918. // quantia minima
  919. // ate a hora
  920. System.out.println("inside");
  921. myRs.close();
  922. // adiciono à tabela de licitacoes
  923. String commandSql = "INSERT INTO bids (AMOUNT, ID_AUCTION, ID_USER, BID_STATE)\n" + "values ("
  924. + amount + ", " + id + ", " + id_user + ", 'active')";
  925. myStmt.executeUpdate(commandSql);
  926.  
  927. check = 1;
  928. myStmt.close();
  929. myStmt2.close();
  930. System.out.println("fim bid");
  931. myConn.commit();
  932.  
  933. } else {
  934. System.out.println("no else");
  935. check = 0;
  936. myRs.close();
  937. myRs2.close();
  938. myStmt.close();
  939. myStmt2.close();
  940. }
  941. } catch (SQLException e) {
  942. System.out.println("catch dentro");
  943. check = 0;
  944. try {
  945. System.out.println("Transaction of bid is being rolled back");
  946. myConn.rollback();
  947. } catch (SQLException e1) {
  948. // TODO Auto-generated catch block
  949. e1.printStackTrace();
  950. }
  951. } catch (ParseException ex) {
  952. Logger.getLogger(RMIServer.class.getName()).log(Level.SEVERE, null, ex);
  953. }
  954. }
  955.  
  956. if (check == 1) {// sempre que uma licita��o for mais baixa que a
  957. // atual, deve ser enviada uma notifica��o a
  958. // todos os utilizadores ligados e que licitaram
  959. System.out.println("baixo in");
  960. resultado = "type: bid, ok: true";
  961. // ENVIO NOTIFICACAO PARA TODAS AS PESSOAS QUE PARTICIPARAM NO
  962. // LEILAO COM BIDS E ESTAO ONLINE
  963. // myRs4 todas as pesoas que fizeram bid naquele leilao excepto o
  964. // proprio e estejam online
  965. try {
  966. myStmt2 = myConn2.createStatement();
  967. myRs4 = myStmt2.executeQuery("SELECT DISTINCT ID_USER\n" + "FROM bids\n" + "WHERE ((ID_AUCTION = " + id
  968. + " AND NOT( ID_USER = " + id_user
  969. + " )) AND ID_USER IN (SELECT ID_USERS FROM USERS WHERE (ONLINE = 1)))");// results
  970. // set
  971.  
  972. while (myRs4.next()) {
  973. try {
  974. client.notification_bid(id, username, amount, getusername(myRs4.getInt("ID_USER")));
  975. } catch (Exception e) {
  976.  
  977. }
  978. try {
  979. client2.notification_bid(id, username, amount, getusername(myRs4.getInt("ID_USER")));
  980. } catch (Exception e) {
  981.  
  982. }
  983.  
  984. }
  985. myRs4.close();
  986. myStmt2.close();
  987. } catch (SQLException ee) {
  988. ee.printStackTrace();
  989. }
  990.  
  991. }
  992. if (check == 0) {
  993. resultado = "type: bid, ok: false";
  994. }
  995. return resultado;
  996. }
  997.  
  998. // LISTAR UTILIZADORES ONLINE
  999. public String online_users() throws RemoteException {
  1000.  
  1001. String resultado;
  1002. String concat = "";
  1003. ResultSet myRs;
  1004. int i = 0;
  1005.  
  1006. // -----------------------------------
  1007. // Verificar utilizadores online
  1008. // -----------------------------------
  1009. Statement myStmt;
  1010. try {
  1011.  
  1012. myStmt = myConn.createStatement();
  1013.  
  1014. myRs = myStmt.executeQuery("SELECT USERNAME\n" + "FROM users\n" + "WHERE ONLINE = 1");// results
  1015. // set
  1016. myRs.first();
  1017.  
  1018. while (!myRs.isLast()) {
  1019. concat += ", users_" + i + "_username: " + myRs.getString("USERNAME");
  1020. i++;
  1021. myRs.next();
  1022. }
  1023.  
  1024. concat += ", users_" + i + "_username: " + myRs.getString("USERNAME");
  1025. } catch (SQLException e) {
  1026.  
  1027. e.printStackTrace();
  1028. }
  1029.  
  1030. resultado = "type : online_users, users_count : " + (i + 1) + concat;
  1031.  
  1032. return resultado;
  1033. }
  1034.  
  1035. // Verificar se um leilão está cancelado
  1036. public int isCancelled(int id_auction) throws RemoteException {
  1037.  
  1038. int check = 0;
  1039. // -------------------------------------
  1040. // Verificar se o registo pode ser feito;
  1041. // -------------------------------------
  1042. Statement myStmt;
  1043. try {
  1044.  
  1045. myStmt = myConn.createStatement();
  1046.  
  1047. ResultSet myRs = myStmt
  1048. .executeQuery("SELECT AUCTION_STATE\n" + "FROM auction\n" + "WHERE ID_AUCTION =" + id_auction);// results
  1049. // set
  1050.  
  1051. myRs.next();
  1052. String estado = myRs.getString("AUCTION_STATE");
  1053.  
  1054. if (estado.equals("cancelled")) {
  1055. check = 1;
  1056. } else {
  1057. check = 0;
  1058. }
  1059.  
  1060. } catch (SQLException e) {// tratar exception de limite de carateres
  1061. e.printStackTrace();
  1062. }
  1063.  
  1064. return check;
  1065. }
  1066.  
  1067. // CANCELAR LEIL�O
  1068. public int cancelAuction(int id_auction) throws RemoteException {
  1069.  
  1070. // atualiza campo state_auction nas tabelas auction e historico
  1071.  
  1072. Statement myStmt;
  1073.  
  1074. if (isCancelled(id_auction) == 0) {// se ainda n�o tiver sido cancelado
  1075. try {
  1076.  
  1077. myStmt = myConn.createStatement();
  1078. myConn.setAutoCommit(false);
  1079.  
  1080. myStmt.executeUpdate(
  1081. "UPDATE auction\n" + "SET AUCTION_STATE = 'cancelled'\n" + "WHERE ID_AUCTION =" + id_auction);// results
  1082. // sets
  1083.  
  1084. // inserir na tabela historico a mudan�a de estado (a partir do
  1085. // id_auction)
  1086. String commandSql = "INSERT INTO historico (ID_AUCTION, TYPE, EDIT)\n" + "values (" + id_auction
  1087. + ", 4, 'active')";
  1088.  
  1089. myStmt.executeUpdate(commandSql); // results set
  1090.  
  1091. myConn.commit();
  1092.  
  1093. } catch (SQLException e) {// tratar exception de limite de carateres
  1094. try {
  1095. System.out.println("Transaction of cancel auction is being rolled back");
  1096. myConn.rollback();
  1097. } catch (SQLException e1) {
  1098. // TODO Auto-generated catch block
  1099. e1.printStackTrace();
  1100. }
  1101. }
  1102.  
  1103. // -----------------------------------
  1104. // Verificar se o leil�o foi cancelado
  1105. // -----------------------------------
  1106. return isCancelled(id_auction);
  1107. } else {// se j� tiver sido cancelado
  1108. return 2;
  1109. }
  1110. }
  1111.  
  1112. public int isBanned(int id_user) throws RemoteException {
  1113. int check = 0;
  1114.  
  1115. Statement myStmt;
  1116. try {
  1117.  
  1118. myStmt = myConn.createStatement();
  1119.  
  1120. ResultSet myRs = myStmt.executeQuery("SELECT USER_STATE\n" + "FROM users\n" + "WHERE ID_USERS =" + id_user);// results
  1121. // set
  1122.  
  1123. myRs.next();
  1124. String estado = myRs.getString("USER_STATE");
  1125.  
  1126. if (estado.equals("banned")) {
  1127. check = 1;
  1128. } else {
  1129. check = 0;
  1130. }
  1131.  
  1132. } catch (SQLException e) {// tratar exception de limite de carateres
  1133. e.printStackTrace();
  1134. }
  1135.  
  1136. return check;
  1137. }
  1138.  
  1139. // BANIR UTILIZADOR
  1140. public int banUser(int id_user) throws RemoteException {
  1141.  
  1142. Statement myStmt;
  1143. Statement myStmt2;
  1144.  
  1145. ArrayList<Integer> bids_auc_u = new ArrayList<Integer>();// array dos
  1146. // leil�es
  1147. // em que o
  1148. // user
  1149. // banido
  1150. // licitou
  1151. // ArrayList<Integer> bids_auc = new ArrayList<Integer>();//array com as
  1152. // bids dos users que licitaram nos mesmos leil�es do user banido
  1153.  
  1154. int min_amount = 0;
  1155. int id = 0;
  1156.  
  1157. int i, j, pos = 0, aux = 0;
  1158.  
  1159. if (isBanned(id_user) == 0) {// se ainda n�o tiver sido banido
  1160. try {
  1161.  
  1162. myStmt = myConn.createStatement();
  1163. // myStmt2 = myConn2.createStatement();
  1164. myConn.setAutoCommit(false);
  1165. // myConn2.setAutoCommit(false);
  1166.  
  1167. // BANIR USER (update do estado de utilizador)
  1168. myStmt.executeUpdate(
  1169. "UPDATE users\n" + "SET USER_STATE = 'banned', ONLINE = 0\n" + "WHERE ID_USERS =" + id_user);// results
  1170. // set
  1171.  
  1172. // CANCELAR LEIL�ES DO USER BANIDO
  1173. myStmt.executeUpdate(
  1174. "UPDATE auction\n" + "SET AUCTION_STATE = 'cancelled'\n" + "WHERE ID_USER =" + id_user);
  1175.  
  1176. ResultSet myRs = myStmt
  1177. .executeQuery("SELECT ID_AUCTION\n" + "FROM auction\n" + "WHERE ID_USER =" + id_user);// results
  1178. // set
  1179.  
  1180. while (myRs.next()) {
  1181.  
  1182. // resultados
  1183. int id_auction = myRs.getInt("ID_AUCTION");
  1184.  
  1185. // inserir no hist�rico todas as altera��es feitas aos
  1186. // leil�es
  1187. String commandSql = "INSERT INTO historico (ID_AUCTION, TYPE, EDIT)\n" + "values (" + id_auction
  1188. + ", 4, 'active')";
  1189. myStmt.executeUpdate(commandSql); // results set
  1190.  
  1191. }
  1192.  
  1193. // APAGAR LICITA�ES E SUBSTITUIR VALORES
  1194. ResultSet myRs2 = myStmt
  1195. .executeQuery("SELECT DISTINCT ID_AUCTION\n" + "FROM bids\n" + "WHERE ID_USER = " + id_user);
  1196.  
  1197. while (myRs2.next()) {
  1198. bids_auc_u.add(myRs2.getInt("ID_AUCTION")); // leil�es em
  1199. // que licitou
  1200. }
  1201.  
  1202. for (i = 0; i < bids_auc_u.size(); i++) {// percorre todos os
  1203. // leil�es em que o
  1204. // user banido
  1205. // licitou
  1206.  
  1207. // bids do utilizador a ser banido por ordem decrescente
  1208. ResultSet myRs3 = myStmt.executeQuery("SELECT AMOUNT\n" + "FROM bids\n" + "WHERE ID_AUCTION = "
  1209. + bids_auc_u.get(i) + " AND ID_USER= \n" + id_user + " ORDER BY AMOUNT DESC");
  1210.  
  1211. // seleciona a minima amount de um utilizador que não o
  1212. // banido
  1213. ResultSet myRs4 = myStmt.executeQuery("SELECT MIN(bids.AMOUNT) AS minim\n" + "FROM bids, auction\n"
  1214. + "WHERE (auction.ID_AUCTION = bids.ID_AUCTION) AND bids.ID_AUCTION = " + bids_auc_u.get(i)
  1215. + " AND bids.ID_USER <> " + id_user + " AND auction.AUCTION_STATE <> 'cancelled'");
  1216.  
  1217. if (myRs4.next()) {
  1218. // min_amount = myRs4.getInt("minim"); // valor da
  1219. // bid
  1220. // minima
  1221.  
  1222. System.out.println("amount ------- " + myRs4.getInt("minim"));
  1223.  
  1224. // vai buscar o id_user que tinha essa min_amount
  1225. ResultSet myRs5 = myStmt.executeQuery("SELECT ID_USER\n" + "FROM bids\n" + "WHERE ID_AUCTION = "
  1226. + bids_auc_u.get(i) + " AND AMOUNT = " + myRs4.getInt("minim"));
  1227.  
  1228. if (myRs5.next()) {
  1229. id = myRs5.getInt("ID_USER");
  1230. System.out.println("-------->" + id);
  1231.  
  1232. if (myRs3.next()) {
  1233. int bid_maisAlta = myRs3.getInt("AMOUNT");// guarda
  1234. // a
  1235. // bid
  1236. // mais
  1237. // alta
  1238. // do
  1239. // utilizador
  1240.  
  1241. String commandSql2 = "INSERT INTO bids (AMOUNT, ID_AUCTION, ID_USER, BID_STATE)\n"
  1242. + "values (" + bid_maisAlta + ", " + bids_auc_u.get(i) + ", " + id
  1243. + ", 'active')";
  1244. myStmt.executeUpdate(commandSql2);
  1245.  
  1246. // inserir a mudança de amount na tabela bids
  1247. /*
  1248. * myStmt.
  1249. * executeUpdate("INSERT INTO bids (ID_AUCTION, AMOUNT, ID_USER, BID_STATE)\n"
  1250. * + " values ("+ bids_auc_u.get(i) + ", " +
  1251. * bid_maisAlta + ", " + id + ",'active')");
  1252. */ // atualiza
  1253. // a
  1254. // aumount
  1255. // na
  1256. // tabela
  1257. // leil�o
  1258.  
  1259. // update do estado da bid
  1260. myStmt.executeUpdate("UPDATE bids\n" + "SET BID_STATE = 'deleted'\n"
  1261. + " WHERE (AMOUNT <" + bid_maisAlta + " OR (AMOUNT =" + bid_maisAlta
  1262. + " AND ID_USER=" + id_user + ")) AND ID_AUCTION=" + bids_auc_u.get(i));// apaga
  1263. // as
  1264. // licita��es
  1265. // do
  1266. // user
  1267. // banido
  1268. // e
  1269. // as
  1270. // mais
  1271. // baixas
  1272.  
  1273. // mandar notifica��o
  1274. String text = "Utilizador " + id_user
  1275. + " foi banido. As licitações foram repostas. Novo melhor valor: "
  1276. + bid_maisAlta;
  1277.  
  1278. System.out.println(message(bids_auc_u.get(i), text, "admin"));
  1279. }
  1280. }
  1281. }
  1282.  
  1283. }
  1284. myConn.commit();
  1285. myStmt.close();
  1286.  
  1287. // myStmt2.close();
  1288.  
  1289. } catch (
  1290.  
  1291. SQLException e) {// tratar exception de limite de carateres
  1292. try {
  1293. System.out.println("Transaction of banUser is being rolled back");
  1294. myConn.rollback();
  1295. } catch (SQLException e1) {
  1296. // TODO Auto-generated catch block
  1297. e1.printStackTrace();
  1298. }
  1299. }
  1300.  
  1301. // -----------------------------------
  1302. // Verificar se o utilizador foi banido
  1303. // -----------------------------------
  1304. return
  1305.  
  1306. isBanned(id_user);
  1307. } else
  1308.  
  1309. {// se o utilizador j� tiver sido banido
  1310. return 2;
  1311. }
  1312. }
  1313.  
  1314. public String stats(int op) throws RemoteException {
  1315.  
  1316. Statement myStmt;
  1317. Statement myStmt2;
  1318.  
  1319. String resultado = "TOP 10\n";
  1320.  
  1321. ArrayList<Integer> users = new ArrayList<>(); // todos os users com
  1322. // leil�es
  1323. ArrayList<Integer> amounts = new ArrayList<>(); // todas as amounts dos
  1324. // leil�es terminated
  1325. ArrayList<Integer> leiloes = new ArrayList<>(); // todas as amounts dos
  1326. // leil�es terminated
  1327. ArrayList<ArrayList<Integer>> cenas = new ArrayList<ArrayList<Integer>>(); // num
  1328. // de
  1329. // leiloes
  1330. // +
  1331. // user
  1332. ArrayList<Integer> ord = new ArrayList<>(); // mais leiloes criados
  1333. // ordenados
  1334. ArrayList<Integer> u_ord = new ArrayList<>(); // users ordenados
  1335. // (corresponde^)
  1336. ArrayList<Integer> u_ord_aux = new ArrayList<>(); // users ordenados
  1337. // (corresponde^)
  1338. int stop = 0, i, j, c, r = 1, aux = 0, var = 1, index = -1;
  1339.  
  1340. try {
  1341.  
  1342. myStmt = myConn.createStatement();
  1343. myStmt2 = myConn2.createStatement();
  1344.  
  1345. // top 10 users leilões criados
  1346. if (op == 1) {
  1347. r = 1;
  1348. // limpar arrays
  1349. leiloes.removeAll(leiloes);
  1350.  
  1351. ResultSet myRs2 = myStmt2.executeQuery(
  1352. "SELECT COUNT(ID_USER) AS num, ID_USER FROM auction GROUP BY ID_USER ORDER BY num DESC");
  1353.  
  1354. while (myRs2.next()) {
  1355. // leiloes.add((myRs2.getInt("COUNT(ID_USER)")));
  1356. leiloes.add(myRs2.getInt("num"));
  1357. leiloes.add(myRs2.getInt("ID_USER"));
  1358. }
  1359.  
  1360. for (c = 0; c < leiloes.size() - 1; c += 2) {
  1361. resultado += (r) + " -> O utilizador com id " + leiloes.get(c + 1) + " criou " + leiloes.get(c)
  1362. + ".\n";
  1363. r++;
  1364. }
  1365.  
  1366. return resultado;
  1367. }
  1368.  
  1369. // top 10 users leilões ganhos
  1370. else if (op == 2) {
  1371. r = 1;
  1372.  
  1373. ResultSet myRs = myStmt.executeQuery(
  1374. "SELECT bids.ID_USER AS id, COUNT(bids.ID_USER) AS top FROM bids,auction WHERE (bids.ID_AUCTION = auction.ID_AUCTION) AND AUCTION_STATE = 'terminated' AND bids.ID_USER <> auction.ID_USER AND AMOUNT = (SELECT MIN(AMOUNT) FROM bids WHERE bids.ID_AUCTION = auction.ID_AUCTION AND BID_STATE = 'active') GROUP BY bids.ID_USER ORDER BY top DESC");
  1375.  
  1376. while (myRs.next()) {
  1377. resultado += (r) + " -> O utilizador com id " + myRs.getInt("id") + " ganhou " + myRs.getInt("top")
  1378. + ".\n";
  1379. r++;
  1380. }
  1381.  
  1382. return resultado;
  1383.  
  1384. }
  1385.  
  1386. // NUMERO DE LEILÕES DOS ÚLTIMOS 10 DIAS
  1387. else if (op == 3) {
  1388.  
  1389. ArrayList<String> deadlines = new ArrayList<>();
  1390.  
  1391. int count = 0;
  1392.  
  1393. ResultSet myRs = myStmt.executeQuery(
  1394. "SELECT ID_AUCTION, DEADLINE\n" + "FROM auction\n" + "WHERE AUCTION_STATE = 'terminated'");
  1395.  
  1396. while (myRs.next()) {
  1397. users.add(myRs.getInt("ID_AUCTION"));
  1398. deadlines.add(myRs.getString("DEADLINE"));
  1399. }
  1400.  
  1401. for (int l = 0; l < deadlines.size(); l++) {
  1402. String dateStart = deadlines.get(l).toString().substring(0, 19);
  1403. String dateStop = getcurrentdate();
  1404.  
  1405. // HH converts hour in 24 hours format (0-23), day
  1406. // calculation
  1407. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1408.  
  1409. Date d1 = null;
  1410. Date d2 = null;
  1411.  
  1412. try {
  1413. d1 = format.parse(dateStart);
  1414. d2 = format.parse(dateStop);
  1415.  
  1416. // in milliseconds
  1417. long diff = Math.abs(d2.getTime() - d1.getTime());
  1418. long diffDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
  1419. // long diffDays = diff / (24 * 60 * 60 * 1000);
  1420.  
  1421. if (diffDays <= 10) {
  1422.  
  1423. System.out.println("d1: " + d1 + " --- d2: " + d2 + " --- diff: " + diffDays);
  1424. count++;
  1425. System.out.println(users.get(l));
  1426. }
  1427.  
  1428. } catch (Exception e) {
  1429. e.printStackTrace();
  1430. }
  1431. }
  1432.  
  1433. resultado = count + " leilões terminados nos últimos 10 dias.\n";
  1434.  
  1435. return resultado;
  1436. }
  1437.  
  1438. } catch (SQLException e) {// tratar exception de limite de carateres
  1439. e.printStackTrace();
  1440. }
  1441.  
  1442. return resultado;
  1443. }
  1444.  
  1445. public void testserver() throws RemoteException {
  1446. return;
  1447.  
  1448. }
  1449.  
  1450. public void populate_deadline_array() throws RemoteException {
  1451.  
  1452. Statement myStmt;
  1453. try {
  1454.  
  1455. myStmt = myConn.createStatement();
  1456. ResultSet myRs = myStmt.executeQuery("SELECT ID_AUCTION, DEADLINE, AUCTION_STATE\n" + "FROM auction");
  1457.  
  1458. while (myRs.next()) {
  1459.  
  1460. if (myRs.getString("AUCTION_STATE").equals("active")) {
  1461. client.writetodeadlinearray(myRs.getInt("ID_AUCTION"),
  1462. myRs.getTimestamp("DEADLINE").toString().substring(0, 19));
  1463. }
  1464. }
  1465.  
  1466. } catch (SQLException e) {
  1467. // TODO Auto-generated catch block
  1468. e.printStackTrace();
  1469. }
  1470.  
  1471. }
  1472.  
  1473. // T�RMINO DO LEIL�O NA DATA, HORA E MINUTO MARCADOS
  1474. public void end_auction(int id) throws RemoteException {
  1475.  
  1476. // ----------------------------------
  1477. // Verificar t�rmino de leiloes
  1478. // -----------------------------------
  1479.  
  1480. try {
  1481. Statement myStmt;
  1482. myConn.setAutoCommit(false);
  1483. myStmt = myConn.createStatement();
  1484.  
  1485. ResultSet myRs = myStmt.executeQuery("SELECT AUCTION_STATE\n" + "FROM auction WHERE ID_AUCTION =" + id);
  1486.  
  1487. myRs.next();
  1488.  
  1489. String estado = myRs.getString("AUCTION_STATE");
  1490.  
  1491. Statement myStmt2;
  1492. myStmt2 = myConn.createStatement();
  1493. myStmt2.executeUpdate("INSERT INTO historico (ID_AUCTION, TYPE, EDIT)\n" + "values (" + id + ", " + 4
  1494. + ", '" + estado + "')");
  1495.  
  1496. Statement myStmt3;
  1497. myStmt3 = myConn.createStatement();
  1498. String sql = "UPDATE auction\n " + "SET AUCTION_STATE = 'terminated'\n" + "WHERE ID_AUCTION = " + id;
  1499. myStmt3.executeUpdate(sql);
  1500.  
  1501. myConn.commit();
  1502.  
  1503. } catch (SQLException e) {
  1504.  
  1505. try {
  1506. System.out.println("Transaction of end_auction is being rolled back");
  1507. myConn.rollback();
  1508. } catch (SQLException e1) {
  1509. // TODO Auto-generated catch block
  1510. e1.printStackTrace();
  1511. }
  1512. }
  1513.  
  1514. }
  1515.  
  1516. public static void main(String args[]) {
  1517. String a;
  1518. try {// ligar � bd
  1519. // connection to database
  1520. myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ibei", "root", "root");
  1521. myConn2 = DriverManager.getConnection("jdbc:mysql://localhost:3306/ibei", "root", "root");
  1522.  
  1523. } catch (Exception exc) {
  1524. exc.printStackTrace();
  1525. }
  1526. System.getProperties().put("java.security.policy", "policy.all");
  1527. System.setSecurityManager(new RMISecurityManager());
  1528.  
  1529. try {
  1530. Registry r = LocateRegistry.createRegistry(6999);
  1531. RMIServer h = new RMIServer();
  1532. r.rebind("RMIServer2", h);
  1533.  
  1534. } catch (Exception ec) {
  1535. int check = 0;
  1536. while (check == 0) {
  1537. try {
  1538. Registry r = LocateRegistry.createRegistry(6999);
  1539. RMIServer h = new RMIServer();
  1540. r.rebind("RMIServer2", h);
  1541. check = 1;
  1542. } catch (Exception e) {
  1543.  
  1544. // e.printStackTrace();
  1545. }
  1546. }
  1547. // System.out.println("Exception caught on RMIServer.main: " + ec);
  1548. }
  1549.  
  1550. }
  1551.  
  1552. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement