Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package rmiserver;
- import java.rmi.*;
- import java.rmi.registry.LocateRegistry;
- import java.rmi.registry.Registry;
- import java.rmi.server.*;
- import java.security.MessageDigest;
- import java.net.*;
- import java.io.*;
- import java.math.BigDecimal;
- import java.math.BigInteger;
- import java.sql.*;
- import java.util.Date;
- import java.util.concurrent.TimeUnit;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import java.util.HashMap;
- import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.util.*;
- public class RMIServer extends UnicastRemoteObject implements RMIServerInterface {
- // static TCPServerInterface client;
- static Connection myConn;
- static Connection myConn2;
- static TCPServerInterface client;
- static TCPServerInterface client2;
- private static final long serialVersionUID = 20141107L;
- private HashMap<String, String> users;
- public RMIServer() throws RemoteException {
- super();
- users = new HashMap<String, String>();
- users.put("bender", "rodriguez"); // static users and passwords, to
- // simplify the example
- users.put("fry", "philip");
- users.put("leela", "turanga");
- users.put("homer", "simpson");
- }
- public boolean userMatchesPassword(String user, String password) throws RemoteException {
- System.out.println("Looking up " + user + "...");
- return users.containsKey(user) && users.get(user).equals(password);
- }
- /**
- * returns all the user names
- */
- public ArrayList<String> getAllUsers() {
- System.out.println("Looking up all users...");
- return new ArrayList<String>(users.keySet());
- }
- public void subscribe(TCPServerInterface c, int i) throws RemoteException {
- if (i == 1) {
- client = c;
- } else {
- client2 = c;
- }
- }
- // M�todos do servidor RMI que o servidor TCP pode usar;
- // REGISTAR CONTA
- public String register(String username, String password) throws RemoteException {
- int check = 0;
- String resultado;
- // -------------------------------------
- // Verificar se o registo pode ser feito;
- // -------------------------------------
- Statement myStmt;
- // PreparedStatement Qusername;
- // PreparedStatement Qpassword;
- //
- // String FindUsername = "SELECT USERNAME\n" + "FROM users\n" + "WHERE
- // USERNAME = ?";
- // String Findpassword = "INSERT INTO users (USERNAME, PASSWORD, ONLINE,
- // USER_STATE)\n " + "VALUES (?, ?, 0, 'active')";
- try {
- myStmt = myConn.createStatement();
- myConn.setAutoCommit(false);
- ResultSet myRs = myStmt
- .executeQuery("SELECT USERNAME\n" + "FROM users\n" + "WHERE USERNAME ='" + username + "'");// results
- // set
- if (myRs.next()) {
- if (myRs.getString("USERNAME").equals(username)) {
- check = 1;
- }
- } else if (check == 0) {
- String sql = "INSERT INTO users (USERNAME, PASSWORD, ONLINE, USER_STATE)\n " + "VALUES ('" + username
- + "', '" + encryptPassword(password) + "', 0, 'active')";
- myStmt.executeUpdate(sql); // results set
- }
- // myRs.close();
- // myStmt.close();
- myConn.commit();
- } catch (SQLException e) {// tratar exception de limite de carateres
- check = 1;
- try {
- System.out.println("Transaction in register is being rolled back");
- myConn.rollback();
- } catch (SQLException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- if (check == 0) {
- resultado = "type: register, ok: true";
- } else {
- resultado = "type: register, ok: false";
- }
- return resultado;
- }
- // FAZER LOGIN
- public String login(String username, String password) throws RemoteException {
- int check = 0;
- String resultado;
- // -----------------------------------
- // Verificar se o login pode ser feito
- // -----------------------------------
- Statement myStmt;
- try {
- myStmt = myConn.createStatement();
- myConn.setAutoCommit(false);
- ResultSet myRs = myStmt.executeQuery("SELECT USERNAME, PASSWORD\n" + "FROM users\n" + "WHERE USERNAME ='"
- + username + "' AND PASSWORD = '" + encryptPassword(password) + "'");// results
- // set
- if (myRs.next()) {
- check = 0;
- String sql = "UPDATE users\n " + "SET ONLINE = 1\n" + "WHERE USERNAME ='" + username
- + "' AND PASSWORD = '" + encryptPassword(password) + "' ";
- myStmt.executeUpdate(sql); // results set
- } else {
- check = 1;
- }
- myConn.commit();
- } catch (SQLException e) {
- check = 1;
- try {
- System.out.println("Transaction in login is being rolled back");
- myConn.rollback();
- } catch (SQLException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- if (check == 0) {
- resultado = "type: login, ok: true";
- } else {
- resultado = "type: login, ok: false";
- }
- return resultado;
- }
- // LOGOUT
- public void logout(String username) throws RemoteException {
- // -----------------------------------
- // LOGOUT
- // -----------------------------------
- Statement myStmt;
- try {
- myConn.setAutoCommit(false);
- myStmt = myConn.createStatement();
- String sql = "UPDATE users\n " + "SET ONLINE = 0\n" + "WHERE USERNAME ='" + username + "'";
- myStmt.executeUpdate(sql); // results set
- myConn.commit();
- } catch (SQLException e) {
- try {
- System.out.println("Transaction in logout is being rolled back");
- myConn.rollback();
- } catch (SQLException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- }
- public boolean isloggedin(String username) throws RemoteException {
- Statement myStmt;
- try {
- myStmt = myConn.createStatement();
- ResultSet myRs = myStmt.executeQuery("SELECT USERNAME\n" + "FROM users\n" + "WHERE USERNAME ='" + username
- + "' AND ONLINE = 1 AND USER_STATE = 'active'");// results
- // set
- if (myRs.next()) {
- return true;
- }
- } catch (SQLException e) {// tratar exception de limite de carateres
- System.out.println("Error in function isloggedin");
- e.printStackTrace();
- }
- return false;
- }
- // CRIAR LEIL�O
- public String create_auction(long code, String title, String description, String Date, int amount, String username)
- throws RemoteException {
- // type: login, username: imota, password: cenasmalucas3
- // type: create_auction, code: 9780451524935, title: 1984, description:
- // big brother i s watching you, deadline: 2017-01-01 00:01, amount: 10
- int check = 0;
- String resultado;
- // -------------------------------------
- // Verificar se o registo pode ser feito;
- // -------------------------------------
- Statement myStmt;
- try {
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date date2 = format.parse(getcurrentdate());
- Date date = format.parse(Date);
- if ((date.compareTo(date2) < 0) || amount <= 0) {
- return "type: create_auction, ok: false";
- }
- myStmt = myConn.createStatement();
- myConn.setAutoCommit(false);
- ResultSet myRs = myStmt
- .executeQuery("SELECT ID_USERS\n" + "FROM users\n" + "WHERE USERNAME ='" + username + "'");// results
- // set
- if (myRs.next()) {
- int id_user = myRs.getInt("ID_USERS");
- String commandSql = "INSERT INTO auction (CODE, TITLE, DESCRIPTION, DEADLINE, ID_USER, AUCTION_STATE)\n"
- + "values (" + code + ", '" + title + "', '" + description + "', '" + Date + "', " + id_user
- + ", 'active')";
- myStmt.executeUpdate(commandSql); // results set
- // para a bid, preciso de saber o ID_AUCTION
- ResultSet myRs2 = myStmt.executeQuery("SELECT ID_AUCTION " + "FROM auction " + "WHERE (CODE =" + code
- + " AND TITLE='" + title + "' AND DESCRIPTION='" + description + "' AND DEADLINE='" + Date
- + "' AND ID_USER=" + id_user + " AND AUCTION_STATE='active')");
- // myRs2.next();
- myRs2.last();
- // adiciona ao array das deadlines a data final da auction
- client.writetodeadlinearray(myRs2.getInt("ID_AUCTION"), Date);
- // acrescento a tabela de bids
- String commandSql2 = "INSERT INTO bids (AMOUNT, ID_AUCTION, ID_USER, BID_STATE)\n" + "values (" + amount
- + ", " + myRs2.getInt("ID_AUCTION") + ", " + id_user + ", 'active')";
- myStmt.executeUpdate(commandSql2);
- check = 1;
- myConn.commit();
- }
- } catch (SQLException e) {// tratar exception de limite de carateres
- check = 0;
- try {
- System.out.println("Transaction of create auction is being rolled back");
- myConn.rollback();
- } catch (SQLException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- } catch (java.text.ParseException ex) {
- Logger.getLogger(RMIServer.class.getName()).log(Level.SEVERE, null, ex);
- }
- // -----------------------------------
- // Verificar se o leil�o foi criado
- // -----------------------------------
- if (check == 1) {
- resultado = "type: create_auction, ok: true";
- } else {
- resultado = "type: create_auction, ok: false";
- }
- return resultado;
- }
- // PESQUISAR POR LEIL�O
- public String search_auction(long code) throws RemoteException {
- // é o code do artigo
- int check = 0;
- String resultado;
- String concat = "";
- int tem_alguma = 0;
- int i = 0;
- Statement myStmt;
- try {
- myStmt = myConn.createStatement();
- ResultSet myRs = myStmt.executeQuery(
- "SELECT ID_AUCTION, CODE, TITLE\n" + "FROM auction\n" + "WHERE CODE =" + BigInteger.valueOf(code));// results
- // set
- while (myRs.next()) {
- concat += ", items_" + i + "_id: " + myRs.getInt("ID_AUCTION") + ", items_" + i + "_code: "
- + myRs.getBigDecimal("CODE") + ", title: " + myRs.getString("TITLE");
- i++;
- tem_alguma = 1;
- }
- // concat += ", items_" + i + "_id: " + myRs.getInt("ID_AUCTION") +
- // ", items_" + i + "_code: " + myRs.getBigDecimal("CODE") + ",
- // title: " + myRs.getString("TITLE");
- check = 1;
- myRs.close();
- } catch (SQLException e) {
- check = 0;
- e.printStackTrace();
- }
- if (check == 1) {
- if (tem_alguma == 1) {
- resultado = "type: search_auction, items_count: " + (i) + concat;
- } else {
- resultado = "type: search_auction, items_count: " + (i);
- }
- } else {
- resultado = "type: search_auction, ok: false";
- }
- return resultado;
- }
- // CONSULTAR DETALHES DE LEIL�O
- public String detail_auction(int id) throws RemoteException {
- String resultado = "";
- // -----------------------------------
- // Verificar detalhes de leil�o
- // -----------------------------------
- Statement myStmt;
- ResultSet myRs;
- String messages = "";
- int i = 0;
- // Calendar cal =Calendar.getInstance();
- try {
- myStmt = myConn.createStatement();
- myRs = myStmt.executeQuery(
- "SELECT TITLE, DESCRIPTION, DEADLINE\n" + "FROM auction\n" + "WHERE ID_AUCTION = " + id);
- myRs.next();
- resultado = "type: detail_auction, title: " + myRs.getString("TITLE") + ", description: "
- + myRs.getString("DESCRIPTION") + ", deadline: "
- + myRs.getTimestamp("DEADLINE").toString().substring(0, 19);
- // myRs.close();
- // myStmt.close();
- ResultSet myRs2;
- Statement myStmt2;
- myStmt2 = myConn.createStatement();
- myRs2 = myStmt2.executeQuery("SELECT ID_USER, TEXT\n" + "FROM messages\n" + "WHERE ID_AUCTION = " + id);
- // myStmt.close();
- while (myRs2.next()) {
- messages += ", message_" + i + "_user: " + getusername(myRs2.getInt("ID_USER")) + ", message_" + i
- + "_text: " + myRs2.getString("TEXT");
- i++;
- }
- resultado += ", messages_count: " + i;
- resultado += messages;
- ResultSet myRs3;
- Statement myStmt3;
- myStmt3 = myConn.createStatement();
- myRs3 = myStmt3
- .executeQuery("SELECT COUNT(AMOUNT) AS BIDS_COUNT\n" + "FROM bids\n" + "WHERE ID_AUCTION = " + id);
- myRs3.next();
- resultado += ", bids_count: " + myRs3.getInt("BIDS_COUNT");
- // myStmt.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return resultado;
- }
- public int getuserid(String username) {
- int id;
- Statement myStmt;
- try {
- myStmt = myConn.createStatement();
- ResultSet myRs = myStmt
- .executeQuery("SELECT ID_USERS\n" + "FROM users\n" + "WHERE USERNAME = '" + username + "'");
- myRs.next();
- id = myRs.getInt("ID_USERS");
- return id;
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return -1;
- }
- public String getcurrentdate() {
- DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- // get current date time with Date()
- Date date = new Date();
- return dateFormat.format(date);
- }
- public String getpreviousmessageowner(int id_auction, int userid) {
- String resposta = "";
- Statement myStmt;
- ResultSet myRs;
- try {
- myStmt = myConn.createStatement();
- myRs = myStmt.executeQuery("SELECT DISTINCT ID_USER\n" + "FROM messages\n" + "WHERE ID_AUCTION = "
- + id_auction + " AND NOT ID_USER = " + userid);// results
- // set
- while (myRs.next()) {
- resposta += myRs.getInt("ID_USER") + "_";
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return resposta;
- }
- // GET USERNAME FROM USER ID
- public String getusername(int id) throws RemoteException {
- String username;
- Statement myStmt;
- try {
- myStmt = myConn.createStatement();
- ResultSet myRs = myStmt.executeQuery("SELECT USERNAME\n" + "FROM users\n" + "WHERE ID_USERS = " + id);
- myRs.next();
- username = myRs.getString("USERNAME");
- return username;
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return "";
- }
- public void sendmessagenotification() throws RemoteException {
- Statement myStmt;
- ResultSet myRs;
- String sendto;
- int auction_id;
- String text;
- int sender_id;
- int msg_id;
- try {
- myStmt = myConn.createStatement();
- myConn.setAutoCommit(false);
- myRs = myStmt.executeQuery("SELECT ID_AUCTION, ID_MSG, TEXT, ID_USER, SENDTO\n" + "FROM messages\n");
- while (myRs.next()) {
- String[] sendto_parsed;
- ArrayList<String> sendto_final = new ArrayList<>();
- String offline = "";
- auction_id = myRs.getInt("ID_AUCTION");
- text = myRs.getString("TEXT");
- sender_id = myRs.getInt("ID_USER");
- msg_id = myRs.getInt("ID_MSG");
- sendto = myRs.getString("SENDTO");
- if (!sendto.equals("")) {
- sendto_parsed = sendto.split("_");
- sendto_final.addAll(Arrays.asList(sendto_parsed));
- for (int i = 0; i < sendto_final.size(); i++) {
- String aux;
- aux = getusername(Integer.parseInt(sendto_final.get(i)));
- if (isloggedin(aux)) {
- try {
- client.message_notification(auction_id, getusername(sender_id), aux, text);
- } catch (Exception e) {
- }
- try {
- client2.message_notification(auction_id, getusername(sender_id), aux, text);
- } catch (Exception e) {
- }
- } else {
- offline += sendto_final.get(i) + "_";
- }
- }
- String sql = "UPDATE messages\n " + "SET SENDTO = '" + offline + "'\n" + "WHERE ID_MSG = " + msg_id;
- myStmt.executeUpdate(sql);
- myConn.commit();
- }
- }
- myRs.close();
- myStmt.close();
- } catch (SQLException e) {
- try {
- System.out.println("Transaction of send message notification is being rolled back");
- myConn.rollback();
- } catch (SQLException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- }
- public String message(int id, String text, String username) throws RemoteException {
- // type: message, id: 1, text: alguma editora em especial?
- // type: login, username: codfish, password: cenasmalucas
- // type: login, username: asilva, password: cenasmalucas2
- // type: login, username: imota, password: cenasmalucas3
- int userid = 0;
- String resultado;
- String date;
- String sendto;
- // -----------------------------------
- // Verificar se foi colocada uma mensagem no mural do leil�o
- // -----------------------------------
- Statement myStmt;
- userid = getuserid(username);
- date = getcurrentdate();
- sendto = getpreviousmessageowner(id, userid);
- try {
- myStmt = myConn.createStatement();
- myConn.setAutoCommit(false);
- // ResultSet myRs;
- String sql = "INSERT INTO messages (ID_AUCTION, TEXT, ID_USER, DATE, SENDTO)\n " + "VALUES (" + id + ", '"
- + text + "', " + userid + ", '" + date + "', '" + sendto + "')";
- myStmt.executeUpdate(sql); // results set
- myStmt.close();
- myConn.commit();
- } catch (SQLException e) {
- resultado = "type: message, ok: false";
- try {
- System.out.println("Transaction of insert message is being rolled back");
- myConn.rollback();
- } catch (SQLException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- return resultado;
- }
- resultado = "type: message, ok: true";
- if (!username.equals("admin")) {
- try {
- client.message_notification(id, username, username, text);
- } catch (Exception e) {
- }
- try {
- client2.message_notification(id, username, username, text);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- sendmessagenotification();
- return resultado;
- }
- public String edit_auction(int id, String edit, String edit_field, String username) throws RemoteException {
- String resultado = "";
- Statement myStmt;
- int check = 0;
- int type = 0;
- try {
- if (edit.toUpperCase().equals("DEADLINE")) {
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date date2 = format.parse(getcurrentdate());
- Date date = format.parse(edit_field);
- if (date.compareTo(date2) < 0) {
- return "type: edit_auction, ok: false";
- }
- type = 3;
- } else if (edit.toUpperCase().equals("DESCRIPTION")) {
- type = 2;
- } else if (edit.toUpperCase().equals("TITLE")) {
- type = 1;
- }
- int idUser = getuserid(username);
- ResultSet myRs;
- Statement myStmt2;
- myStmt2 = myConn.createStatement();
- myConn.setAutoCommit(false);
- myRs = myStmt2.executeQuery("SELECT ID_USER FROM auction WHERE ID_AUCTION = " + id);
- myRs.next();
- if (myRs.getInt("ID_USER") != idUser) {
- return "type: edit_auction, ok: false";
- }
- myRs = myStmt2.executeQuery(
- "SELECT " + edit.toUpperCase() + "\n" + "FROM auction\n" + "WHERE ID_AUCTION = " + id);
- myRs.next();
- // myStmt2.close();
- Statement myStmt3;
- myStmt3 = myConn.createStatement();
- String commandSql4 = "INSERT INTO historico (ID_AUCTION, TYPE, EDIT)\n" + "values (" + id + ", " + type
- + ", '" + myRs.getString(edit.toUpperCase()) + "')";
- myStmt3.executeUpdate(commandSql4);
- // myStmt3.close();
- myStmt = myConn.createStatement();
- String sql = "UPDATE auction\n " + "SET " + edit.toUpperCase() + " = '" + edit_field + "'\n"
- + "WHERE ID_AUCTION = " + id;
- myStmt.executeUpdate(sql); // results set
- // myStmt.close();
- myConn.commit();
- } catch (SQLException e) {
- check = 1;
- try {
- System.out.println("Transaction of edit_auction is being rolled back");
- myConn.rollback();
- } catch (SQLException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- } catch (java.text.ParseException ex) {
- Logger.getLogger(RMIServer.class.getName()).log(Level.SEVERE, null, ex);
- }
- if (check == 0) {
- resultado = "type: edit_auction, ok: true";
- /*
- * ResultSet myRs; try { myStmt = myConn.createStatement(); myRs =
- * myStmt.executeQuery("SELECT *\n" + "FROM auction\n" +
- * "WHERE ID_AUCTION = " + id); myRs.next();
- *
- * String commandSql4 =
- * "INSERT INTO historico (CODE, TITLE, DESCRIPTION, DEADLINE, AMOUNT, BIDS_COUNT, ID_USER, ID_AUCTION, AUCTION_STATE)\n"
- * + "values (" + myRs.getBigDecimal("CODE") + ", '" +
- * myRs.getString("TITLE") + "', '" + myRs.getString("DESCRIPTION")
- * + "', '" + myRs.getString("DEADLINE") + "', " +
- * myRs.getInt("AMOUNT") + ", " + myRs.getInt("BIDS_COUNT") + ", " +
- * myRs.getInt("ID_USER") + ", " + myRs.getInt("ID_AUCTION") + ", '"
- * + myRs.getString("AUCTION_STATE") + "')";
- * myStmt.executeUpdate(commandSql4);
- *
- * } catch (SQLException e) {
- *
- * e.printStackTrace(); }
- */
- } else {
- resultado = "type: edit_auction, ok: false";
- }
- return resultado;
- }
- public String encryptPassword(String base) {
- try {
- MessageDigest digest = MessageDigest.getInstance("SHA-256");
- byte[] hash = digest.digest(base.getBytes("UTF-8"));
- StringBuffer hexString = new StringBuffer();
- for (int i = 0; i < hash.length; i++) {
- String hex = Integer.toHexString(0xff & hash[i]);
- if (hex.length() == 1)
- hexString.append('0');
- hexString.append(hex);
- }
- return hexString.toString();
- } catch (Exception ex) {
- throw new RuntimeException(ex);
- }
- }
- // CONSULTAR TODOS OS LEIL�ES EM QUE O UTILIZADOR TENHA ATIVIDADE
- public String my_auctions(String username) throws RemoteException {
- int check = 0;
- String resultado;
- // -----------------------------------
- // Verifico se username pode ser repetido ou nao?
- // -----------------------------------
- String concat = "";
- int i = 0;
- int tem_alguma = 0;
- int id_user;
- Statement myStmt;
- // Statement myStmt2;
- try {
- myStmt = myConn.createStatement();
- // myStmt2 = myConn2.createStatement();
- ResultSet myRs = myStmt.executeQuery(
- "SELECT USERNAME, ID_USERS\n" + "FROM users\n" + "WHERE USERNAME = '" + username + "'");// results
- // set
- myRs.next();
- id_user = myRs.getInt("ID_USERS");
- myRs.close();
- // get bids do utilizador
- // ResultSet myRs3 = myStmt2.executeQuery("SELECT DISTINCT
- // ID_AUCTION\n"
- // + "FROM bids\n"
- // + "WHERE ID_USER =" + id_user +"AND ID_AUCTION IN SELECT DISTINCT
- // ID_AUCTION, CODE,);
- //
- //
- // get leiloes do utilizador
- ResultSet myRs2 = myStmt.executeQuery("SELECT DISTINCT ID_AUCTION, CODE, TITLE, ID_USER, AUCTION_STATE\n"
- + "FROM auction\n" + "WHERE (ID_USER = " + id_user
- + " OR ID_AUCTION IN (SELECT DISTINCT ID_AUCTION FROM bids WHERE ID_USER = " + id_user + "))");
- // edit cima!
- while (myRs2.next()) {
- concat += ", items_" + i + "_id: " + myRs2.getInt("ID_AUCTION") + ", items_" + i + "_code: "
- + myRs2.getBigDecimal("CODE") + ", title: " + myRs2.getString("TITLE");
- i++;
- tem_alguma = 1;
- }
- // concat += ", items_" + i + "_id: " + myRs2.getInt("ID_AUCTION") +
- // ", items_" + i + "_code: " + myRs2.getBigDecimal("CODE") + ",
- // title: " + myRs2.getString("TITLE");
- myRs2.close();
- check = 1;
- myRs2.close();
- } catch (SQLException e) {
- check = 0;
- e.printStackTrace();
- }
- if (check == 1) {
- if (tem_alguma == 1) {
- resultado = "type: my_auctions, items_count: " + (i) + concat;
- } else {
- resultado = "type: my_auctions, items_count: " + (i);
- }
- } else {
- resultado = "type: my_auctions, ok: false";
- }
- return resultado;
- }
- public boolean isTerminated(int id_auction) {
- Statement myStmt;
- try {
- myStmt = myConn.createStatement();
- ResultSet myRs = myStmt
- .executeQuery("SELECT AUCTION_STATE\n" + "FROM auction\n" + "WHERE ID_AUCTION = " + id_auction);// results
- // set
- myRs.next();
- if (myRs.getString("AUCTION_STATE").equals("terminated")) {
- return true;
- }
- } catch (SQLException ex) {
- Logger.getLogger(RMIServer.class.getName()).log(Level.SEVERE, null, ex);
- }
- return false;
- }
- // EFETUAR UMA LICITA��O NUM LEIL�O
- public String bid(int id, int amount, String username) throws RemoteException, java.text.ParseException {
- int check = 0;
- String resultado = "";
- Date date;
- int aux_id_alteracao = 0;
- int aux_amount = 0;
- int aux = 0;
- int id_user = 0;
- // -----------------------------------
- // Verifico se username pode ser repetido ou nao?
- // -----------------------------------
- String concat = "";
- int i = 0;
- Statement myStmt;
- Statement myStmt2;
- ResultSet myRs4;
- int val_bids_count;
- if ((isCancelled(id) == 0) && !isTerminated(id) && isloggedin(username)) {
- try {
- myStmt = myConn.createStatement();
- myStmt2 = myConn2.createStatement();
- myConn.setAutoCommit(false);
- // myConn2.setAutoCommit(false);
- // dá-me o valor(amount) atual do leilao
- ResultSet myRs = myStmt2.executeQuery("SELECT MIN(bids.AMOUNT) AS min_amount, auction.DEADLINE\n"
- + "FROM bids, auction\n" + "WHERE auction.ID_AUCTION = " + id
- + " AND bids.ID_AUCTION = auction.ID_AUCTION AND (NOT(bids.BID_STATE = 'cancelled'))");// results
- // set
- // preciso do ID_user
- ResultSet myRs2 = myStmt
- .executeQuery("SELECT ID_USERS\n" + "FROM users\n" + "WHERE USERNAME = '" + username + "'");// results
- // set
- myRs2.next();
- id_user = myRs2.getInt("ID_USERS");
- // myRs2 = myStmt.executeQuery("SELECT ID_ALTERACAO, AMOUNT\n"
- // + "FROM historico\n"
- // + "WHERE ID_AUCTION = " + id);
- //
- // while (myRs2.next()) {
- // if (aux == 0) {
- // aux_id_alteracao = myRs2.getInt("ID_ALTERACAO");
- // aux_amount_inicial = myRs2.getInt("AMOUNT");
- // aux++;
- // } else if (myRs2.getInt("ID_ALTERACAO") < aux_id_alteracao) {
- // aux_id_alteracao = myRs2.getInt("ID_ALTERACAO");
- // aux_amount_inicial = myRs2.getInt("AMOUNT");
- // }
- // }
- // myRs2.close();
- if (isBanned(id_user) == 1) {
- System.out.println("User banido");
- return "type: bid, ok: false";
- }
- // aux_amount=myRs.getInt("min_amount");
- //
- // if (amount > aux_amount) {
- // System.out.println("quantia da licitacao maior que quantia
- // minima");
- // return "type: bid, ok: false";
- // }
- //
- System.out.println("next");
- myRs.next();
- if ((amount < myRs.getInt("min_amount"))|| amount>=0) {// so aceita valores
- // menores que
- // quantia minima
- // ate a hora
- System.out.println("inside");
- myRs.close();
- // adiciono à tabela de licitacoes
- String commandSql = "INSERT INTO bids (AMOUNT, ID_AUCTION, ID_USER, BID_STATE)\n" + "values ("
- + amount + ", " + id + ", " + id_user + ", 'active')";
- myStmt.executeUpdate(commandSql);
- check = 1;
- myStmt.close();
- myStmt2.close();
- System.out.println("fim bid");
- myConn.commit();
- } else {
- System.out.println("no else");
- check = 0;
- myRs.close();
- myRs2.close();
- myStmt.close();
- myStmt2.close();
- }
- } catch (SQLException e) {
- System.out.println("catch dentro");
- check = 0;
- try {
- System.out.println("Transaction of bid is being rolled back");
- myConn.rollback();
- } catch (SQLException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- } catch (ParseException ex) {
- Logger.getLogger(RMIServer.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- if (check == 1) {// sempre que uma licita��o for mais baixa que a
- // atual, deve ser enviada uma notifica��o a
- // todos os utilizadores ligados e que licitaram
- System.out.println("baixo in");
- resultado = "type: bid, ok: true";
- // ENVIO NOTIFICACAO PARA TODAS AS PESSOAS QUE PARTICIPARAM NO
- // LEILAO COM BIDS E ESTAO ONLINE
- // myRs4 todas as pesoas que fizeram bid naquele leilao excepto o
- // proprio e estejam online
- try {
- myStmt2 = myConn2.createStatement();
- myRs4 = myStmt2.executeQuery("SELECT DISTINCT ID_USER\n" + "FROM bids\n" + "WHERE ((ID_AUCTION = " + id
- + " AND NOT( ID_USER = " + id_user
- + " )) AND ID_USER IN (SELECT ID_USERS FROM USERS WHERE (ONLINE = 1)))");// results
- // set
- while (myRs4.next()) {
- try {
- client.notification_bid(id, username, amount, getusername(myRs4.getInt("ID_USER")));
- } catch (Exception e) {
- }
- try {
- client2.notification_bid(id, username, amount, getusername(myRs4.getInt("ID_USER")));
- } catch (Exception e) {
- }
- }
- myRs4.close();
- myStmt2.close();
- } catch (SQLException ee) {
- ee.printStackTrace();
- }
- }
- if (check == 0) {
- resultado = "type: bid, ok: false";
- }
- return resultado;
- }
- // LISTAR UTILIZADORES ONLINE
- public String online_users() throws RemoteException {
- String resultado;
- String concat = "";
- ResultSet myRs;
- int i = 0;
- // -----------------------------------
- // Verificar utilizadores online
- // -----------------------------------
- Statement myStmt;
- try {
- myStmt = myConn.createStatement();
- myRs = myStmt.executeQuery("SELECT USERNAME\n" + "FROM users\n" + "WHERE ONLINE = 1");// results
- // set
- myRs.first();
- while (!myRs.isLast()) {
- concat += ", users_" + i + "_username: " + myRs.getString("USERNAME");
- i++;
- myRs.next();
- }
- concat += ", users_" + i + "_username: " + myRs.getString("USERNAME");
- } catch (SQLException e) {
- e.printStackTrace();
- }
- resultado = "type : online_users, users_count : " + (i + 1) + concat;
- return resultado;
- }
- // Verificar se um leilão está cancelado
- public int isCancelled(int id_auction) throws RemoteException {
- int check = 0;
- // -------------------------------------
- // Verificar se o registo pode ser feito;
- // -------------------------------------
- Statement myStmt;
- try {
- myStmt = myConn.createStatement();
- ResultSet myRs = myStmt
- .executeQuery("SELECT AUCTION_STATE\n" + "FROM auction\n" + "WHERE ID_AUCTION =" + id_auction);// results
- // set
- myRs.next();
- String estado = myRs.getString("AUCTION_STATE");
- if (estado.equals("cancelled")) {
- check = 1;
- } else {
- check = 0;
- }
- } catch (SQLException e) {// tratar exception de limite de carateres
- e.printStackTrace();
- }
- return check;
- }
- // CANCELAR LEIL�O
- public int cancelAuction(int id_auction) throws RemoteException {
- // atualiza campo state_auction nas tabelas auction e historico
- Statement myStmt;
- if (isCancelled(id_auction) == 0) {// se ainda n�o tiver sido cancelado
- try {
- myStmt = myConn.createStatement();
- myConn.setAutoCommit(false);
- myStmt.executeUpdate(
- "UPDATE auction\n" + "SET AUCTION_STATE = 'cancelled'\n" + "WHERE ID_AUCTION =" + id_auction);// results
- // sets
- // inserir na tabela historico a mudan�a de estado (a partir do
- // id_auction)
- String commandSql = "INSERT INTO historico (ID_AUCTION, TYPE, EDIT)\n" + "values (" + id_auction
- + ", 4, 'active')";
- myStmt.executeUpdate(commandSql); // results set
- myConn.commit();
- } catch (SQLException e) {// tratar exception de limite de carateres
- try {
- System.out.println("Transaction of cancel auction is being rolled back");
- myConn.rollback();
- } catch (SQLException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- // -----------------------------------
- // Verificar se o leil�o foi cancelado
- // -----------------------------------
- return isCancelled(id_auction);
- } else {// se j� tiver sido cancelado
- return 2;
- }
- }
- public int isBanned(int id_user) throws RemoteException {
- int check = 0;
- Statement myStmt;
- try {
- myStmt = myConn.createStatement();
- ResultSet myRs = myStmt.executeQuery("SELECT USER_STATE\n" + "FROM users\n" + "WHERE ID_USERS =" + id_user);// results
- // set
- myRs.next();
- String estado = myRs.getString("USER_STATE");
- if (estado.equals("banned")) {
- check = 1;
- } else {
- check = 0;
- }
- } catch (SQLException e) {// tratar exception de limite de carateres
- e.printStackTrace();
- }
- return check;
- }
- // BANIR UTILIZADOR
- public int banUser(int id_user) throws RemoteException {
- Statement myStmt;
- Statement myStmt2;
- ArrayList<Integer> bids_auc_u = new ArrayList<Integer>();// array dos
- // leil�es
- // em que o
- // user
- // banido
- // licitou
- // ArrayList<Integer> bids_auc = new ArrayList<Integer>();//array com as
- // bids dos users que licitaram nos mesmos leil�es do user banido
- int min_amount = 0;
- int id = 0;
- int i, j, pos = 0, aux = 0;
- if (isBanned(id_user) == 0) {// se ainda n�o tiver sido banido
- try {
- myStmt = myConn.createStatement();
- // myStmt2 = myConn2.createStatement();
- myConn.setAutoCommit(false);
- // myConn2.setAutoCommit(false);
- // BANIR USER (update do estado de utilizador)
- myStmt.executeUpdate(
- "UPDATE users\n" + "SET USER_STATE = 'banned', ONLINE = 0\n" + "WHERE ID_USERS =" + id_user);// results
- // set
- // CANCELAR LEIL�ES DO USER BANIDO
- myStmt.executeUpdate(
- "UPDATE auction\n" + "SET AUCTION_STATE = 'cancelled'\n" + "WHERE ID_USER =" + id_user);
- ResultSet myRs = myStmt
- .executeQuery("SELECT ID_AUCTION\n" + "FROM auction\n" + "WHERE ID_USER =" + id_user);// results
- // set
- while (myRs.next()) {
- // resultados
- int id_auction = myRs.getInt("ID_AUCTION");
- // inserir no hist�rico todas as altera��es feitas aos
- // leil�es
- String commandSql = "INSERT INTO historico (ID_AUCTION, TYPE, EDIT)\n" + "values (" + id_auction
- + ", 4, 'active')";
- myStmt.executeUpdate(commandSql); // results set
- }
- // APAGAR LICITA�ES E SUBSTITUIR VALORES
- ResultSet myRs2 = myStmt
- .executeQuery("SELECT DISTINCT ID_AUCTION\n" + "FROM bids\n" + "WHERE ID_USER = " + id_user);
- while (myRs2.next()) {
- bids_auc_u.add(myRs2.getInt("ID_AUCTION")); // leil�es em
- // que licitou
- }
- for (i = 0; i < bids_auc_u.size(); i++) {// percorre todos os
- // leil�es em que o
- // user banido
- // licitou
- // bids do utilizador a ser banido por ordem decrescente
- ResultSet myRs3 = myStmt.executeQuery("SELECT AMOUNT\n" + "FROM bids\n" + "WHERE ID_AUCTION = "
- + bids_auc_u.get(i) + " AND ID_USER= \n" + id_user + " ORDER BY AMOUNT DESC");
- // seleciona a minima amount de um utilizador que não o
- // banido
- ResultSet myRs4 = myStmt.executeQuery("SELECT MIN(bids.AMOUNT) AS minim\n" + "FROM bids, auction\n"
- + "WHERE (auction.ID_AUCTION = bids.ID_AUCTION) AND bids.ID_AUCTION = " + bids_auc_u.get(i)
- + " AND bids.ID_USER <> " + id_user + " AND auction.AUCTION_STATE <> 'cancelled'");
- if (myRs4.next()) {
- // min_amount = myRs4.getInt("minim"); // valor da
- // bid
- // minima
- System.out.println("amount ------- " + myRs4.getInt("minim"));
- // vai buscar o id_user que tinha essa min_amount
- ResultSet myRs5 = myStmt.executeQuery("SELECT ID_USER\n" + "FROM bids\n" + "WHERE ID_AUCTION = "
- + bids_auc_u.get(i) + " AND AMOUNT = " + myRs4.getInt("minim"));
- if (myRs5.next()) {
- id = myRs5.getInt("ID_USER");
- System.out.println("-------->" + id);
- if (myRs3.next()) {
- int bid_maisAlta = myRs3.getInt("AMOUNT");// guarda
- // a
- // bid
- // mais
- // alta
- // do
- // utilizador
- String commandSql2 = "INSERT INTO bids (AMOUNT, ID_AUCTION, ID_USER, BID_STATE)\n"
- + "values (" + bid_maisAlta + ", " + bids_auc_u.get(i) + ", " + id
- + ", 'active')";
- myStmt.executeUpdate(commandSql2);
- // inserir a mudança de amount na tabela bids
- /*
- * myStmt.
- * executeUpdate("INSERT INTO bids (ID_AUCTION, AMOUNT, ID_USER, BID_STATE)\n"
- * + " values ("+ bids_auc_u.get(i) + ", " +
- * bid_maisAlta + ", " + id + ",'active')");
- */ // atualiza
- // a
- // aumount
- // na
- // tabela
- // leil�o
- // update do estado da bid
- myStmt.executeUpdate("UPDATE bids\n" + "SET BID_STATE = 'deleted'\n"
- + " WHERE (AMOUNT <" + bid_maisAlta + " OR (AMOUNT =" + bid_maisAlta
- + " AND ID_USER=" + id_user + ")) AND ID_AUCTION=" + bids_auc_u.get(i));// apaga
- // as
- // licita��es
- // do
- // user
- // banido
- // e
- // as
- // mais
- // baixas
- // mandar notifica��o
- String text = "Utilizador " + id_user
- + " foi banido. As licitações foram repostas. Novo melhor valor: "
- + bid_maisAlta;
- System.out.println(message(bids_auc_u.get(i), text, "admin"));
- }
- }
- }
- }
- myConn.commit();
- myStmt.close();
- // myStmt2.close();
- } catch (
- SQLException e) {// tratar exception de limite de carateres
- try {
- System.out.println("Transaction of banUser is being rolled back");
- myConn.rollback();
- } catch (SQLException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- // -----------------------------------
- // Verificar se o utilizador foi banido
- // -----------------------------------
- return
- isBanned(id_user);
- } else
- {// se o utilizador j� tiver sido banido
- return 2;
- }
- }
- public String stats(int op) throws RemoteException {
- Statement myStmt;
- Statement myStmt2;
- String resultado = "TOP 10\n";
- ArrayList<Integer> users = new ArrayList<>(); // todos os users com
- // leil�es
- ArrayList<Integer> amounts = new ArrayList<>(); // todas as amounts dos
- // leil�es terminated
- ArrayList<Integer> leiloes = new ArrayList<>(); // todas as amounts dos
- // leil�es terminated
- ArrayList<ArrayList<Integer>> cenas = new ArrayList<ArrayList<Integer>>(); // num
- // de
- // leiloes
- // +
- // user
- ArrayList<Integer> ord = new ArrayList<>(); // mais leiloes criados
- // ordenados
- ArrayList<Integer> u_ord = new ArrayList<>(); // users ordenados
- // (corresponde^)
- ArrayList<Integer> u_ord_aux = new ArrayList<>(); // users ordenados
- // (corresponde^)
- int stop = 0, i, j, c, r = 1, aux = 0, var = 1, index = -1;
- try {
- myStmt = myConn.createStatement();
- myStmt2 = myConn2.createStatement();
- // top 10 users leilões criados
- if (op == 1) {
- r = 1;
- // limpar arrays
- leiloes.removeAll(leiloes);
- ResultSet myRs2 = myStmt2.executeQuery(
- "SELECT COUNT(ID_USER) AS num, ID_USER FROM auction GROUP BY ID_USER ORDER BY num DESC");
- while (myRs2.next()) {
- // leiloes.add((myRs2.getInt("COUNT(ID_USER)")));
- leiloes.add(myRs2.getInt("num"));
- leiloes.add(myRs2.getInt("ID_USER"));
- }
- for (c = 0; c < leiloes.size() - 1; c += 2) {
- resultado += (r) + " -> O utilizador com id " + leiloes.get(c + 1) + " criou " + leiloes.get(c)
- + ".\n";
- r++;
- }
- return resultado;
- }
- // top 10 users leilões ganhos
- else if (op == 2) {
- r = 1;
- ResultSet myRs = myStmt.executeQuery(
- "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");
- while (myRs.next()) {
- resultado += (r) + " -> O utilizador com id " + myRs.getInt("id") + " ganhou " + myRs.getInt("top")
- + ".\n";
- r++;
- }
- return resultado;
- }
- // NUMERO DE LEILÕES DOS ÚLTIMOS 10 DIAS
- else if (op == 3) {
- ArrayList<String> deadlines = new ArrayList<>();
- int count = 0;
- ResultSet myRs = myStmt.executeQuery(
- "SELECT ID_AUCTION, DEADLINE\n" + "FROM auction\n" + "WHERE AUCTION_STATE = 'terminated'");
- while (myRs.next()) {
- users.add(myRs.getInt("ID_AUCTION"));
- deadlines.add(myRs.getString("DEADLINE"));
- }
- for (int l = 0; l < deadlines.size(); l++) {
- String dateStart = deadlines.get(l).toString().substring(0, 19);
- String dateStop = getcurrentdate();
- // HH converts hour in 24 hours format (0-23), day
- // calculation
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date d1 = null;
- Date d2 = null;
- try {
- d1 = format.parse(dateStart);
- d2 = format.parse(dateStop);
- // in milliseconds
- long diff = Math.abs(d2.getTime() - d1.getTime());
- long diffDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
- // long diffDays = diff / (24 * 60 * 60 * 1000);
- if (diffDays <= 10) {
- System.out.println("d1: " + d1 + " --- d2: " + d2 + " --- diff: " + diffDays);
- count++;
- System.out.println(users.get(l));
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- resultado = count + " leilões terminados nos últimos 10 dias.\n";
- return resultado;
- }
- } catch (SQLException e) {// tratar exception de limite de carateres
- e.printStackTrace();
- }
- return resultado;
- }
- public void testserver() throws RemoteException {
- return;
- }
- public void populate_deadline_array() throws RemoteException {
- Statement myStmt;
- try {
- myStmt = myConn.createStatement();
- ResultSet myRs = myStmt.executeQuery("SELECT ID_AUCTION, DEADLINE, AUCTION_STATE\n" + "FROM auction");
- while (myRs.next()) {
- if (myRs.getString("AUCTION_STATE").equals("active")) {
- client.writetodeadlinearray(myRs.getInt("ID_AUCTION"),
- myRs.getTimestamp("DEADLINE").toString().substring(0, 19));
- }
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- // T�RMINO DO LEIL�O NA DATA, HORA E MINUTO MARCADOS
- public void end_auction(int id) throws RemoteException {
- // ----------------------------------
- // Verificar t�rmino de leiloes
- // -----------------------------------
- try {
- Statement myStmt;
- myConn.setAutoCommit(false);
- myStmt = myConn.createStatement();
- ResultSet myRs = myStmt.executeQuery("SELECT AUCTION_STATE\n" + "FROM auction WHERE ID_AUCTION =" + id);
- myRs.next();
- String estado = myRs.getString("AUCTION_STATE");
- Statement myStmt2;
- myStmt2 = myConn.createStatement();
- myStmt2.executeUpdate("INSERT INTO historico (ID_AUCTION, TYPE, EDIT)\n" + "values (" + id + ", " + 4
- + ", '" + estado + "')");
- Statement myStmt3;
- myStmt3 = myConn.createStatement();
- String sql = "UPDATE auction\n " + "SET AUCTION_STATE = 'terminated'\n" + "WHERE ID_AUCTION = " + id;
- myStmt3.executeUpdate(sql);
- myConn.commit();
- } catch (SQLException e) {
- try {
- System.out.println("Transaction of end_auction is being rolled back");
- myConn.rollback();
- } catch (SQLException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- }
- public static void main(String args[]) {
- String a;
- try {// ligar � bd
- // connection to database
- myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ibei", "root", "root");
- myConn2 = DriverManager.getConnection("jdbc:mysql://localhost:3306/ibei", "root", "root");
- } catch (Exception exc) {
- exc.printStackTrace();
- }
- System.getProperties().put("java.security.policy", "policy.all");
- System.setSecurityManager(new RMISecurityManager());
- try {
- Registry r = LocateRegistry.createRegistry(6999);
- RMIServer h = new RMIServer();
- r.rebind("RMIServer2", h);
- } catch (Exception ec) {
- int check = 0;
- while (check == 0) {
- try {
- Registry r = LocateRegistry.createRegistry(6999);
- RMIServer h = new RMIServer();
- r.rebind("RMIServer2", h);
- check = 1;
- } catch (Exception e) {
- // e.printStackTrace();
- }
- }
- // System.out.println("Exception caught on RMIServer.main: " + ec);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement