Advertisement
Guest User

RMIServer2

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