SHARE
TWEET

Untitled

a guest Sep 12th, 2019 140 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.dev.costela.database.client;
  2.  
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.util.Collection;
  7. import java.util.Collections;
  8. import java.util.Map;
  9. import java.util.UUID;
  10. import java.util.concurrent.atomic.AtomicInteger;
  11.  
  12. import org.bukkit.entity.Player;
  13. import org.bukkit.event.EventHandler;
  14. import org.bukkit.event.EventPriority;
  15. import org.bukkit.event.Listener;
  16. import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
  17. import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result;
  18. import org.bukkit.event.player.PlayerLoginEvent;
  19.  
  20. import com.dev.costela.Main;
  21. import com.dev.costela.database.SQLWriter;
  22. import com.google.common.collect.Maps;
  23.  
  24. /*
  25.  * The Client is a pre loaded version of GamePlayer that loads before JoinEvent is called.
  26.  * While the client data is loading the thread is locked.
  27.  *
  28.  * Clients shutdowns (saving important informations like encrypted player's password) to database on OverlandsClientLoginEvent,
  29.  * this event is called after PlayerJoinEvent > after /register or /login command. Otherwise client will be removed after a timeout.
  30.  */
  31. public class ClientCore implements Listener {
  32.  
  33.     private Map<UUID, Client> users;
  34.     private Map<String, Object> lockMap;
  35.     private Object lock = new Object();
  36.     private AtomicInteger clientsConnecting;
  37.     private AtomicInteger clientsProcessing;
  38.    
  39.     public ClientCore() {
  40.         users = Collections.synchronizedMap(Maps.newHashMap());
  41.         lockMap = Collections.synchronizedMap(Maps.newHashMap());
  42.         clientsProcessing = new AtomicInteger(0);
  43.         clientsConnecting = new AtomicInteger(0);
  44.     }
  45.  
  46.     @EventHandler(priority = EventPriority.LOWEST)
  47.     public void connectAndProcessClient(AsyncPlayerPreLoginEvent event) {
  48.        
  49.         try {
  50.             clientsConnecting.incrementAndGet(); //Client's connecting.
  51.             try {
  52.                 while (clientsProcessing.get() >= 5) { //Thread must do a quick sleep to avoid over processing.
  53.                     Thread.sleep(30); //Thread sleep, login locked during 30ms
  54.                 }
  55.             } catch (InterruptedException ex) {
  56.                 ex.printStackTrace();
  57.             }
  58.             try {
  59.                 clientsProcessing.incrementAndGet(); //Client's processing.
  60.                 Main.clientManager.addPlayer(event.getUniqueId());
  61.                 if(!load(addClient(event.getUniqueId()), event.getName(), event.getUniqueId(), event.getAddress().getHostAddress())) {
  62.                     event.disallow(Result.KICK_OTHER, "§cTente reconectar em 3 segundos.");
  63.                 }
  64.             } catch (Exception ex) {
  65.                 event.disallow(Result.KICK_OTHER, "§cErro ao carregar data, tente novamente.");
  66.             } finally {
  67.                 clientsProcessing.decrementAndGet();
  68.             }
  69.         } finally {
  70.             clientsConnecting.decrementAndGet();
  71.         }
  72.     }
  73.  
  74.     @EventHandler(priority = EventPriority.MONITOR)
  75.     public void processLogin(PlayerLoginEvent e) {
  76.         synchronized (lock) {
  77.             if (!users.containsKey(e.getPlayer().getUniqueId())) {
  78.                 users.put(e.getPlayer().getUniqueId(), new Client(e.getPlayer().getUniqueId()));
  79.             }
  80.         }
  81.  
  82.         Client client = get(e.getPlayer().getUniqueId());
  83.         if (client == null || client.getRank() == null) {
  84.             e.disallow(PlayerLoginEvent.Result.KICK_OTHER, "§cErro ao carregar data, tente reconectar.");
  85.             return;
  86.         }
  87.  
  88.         client.setPlayer(e.getPlayer());
  89.         client.setName(e.getPlayer().getName());
  90.  
  91.         /*if (client.isBanned()) {
  92.             e.disallow(PlayerLoginEvent.Result.KICK_OTHER, MessageUtil.color("&cVocê está banido do servidor. "
  93.                     + "\n" + client.getBanReason() + "\n" +
  94.                     " \n" +
  95.                     "&fTempo restante: &c" + getBanManager().getTimeLeft(client.getBanEnd())));
  96.            
  97.             delete(client.getUuid());
  98.             return;
  99.         }*/
  100.  
  101.         Main.get().getLogger().info("Client with name " +  e.getPlayer().getName() + " was loaded.");
  102.        
  103.     }
  104.  
  105.     public boolean load(Client client, String name, UUID uuid, String ip) {
  106.         long operationStart = System.currentTimeMillis();
  107.        
  108.         lockMap.put(name, new Object());
  109.        
  110.         new SQLWriter() {
  111.             int accountId = -1;
  112.             ResultSet resultSet = null;
  113.             PreparedStatement preparedStatement = null;
  114.             PreparedStatement preparedStatementInfo = null;
  115.             @Override
  116.             public void onWrite() throws SQLException {
  117.                 try {
  118.                     if(!Main.getDataManager().checkPlayer(uuid.toString())) {
  119.                         preparedStatementInfo = Main.get().getDB().getConnection().get().prepareStatement("INSERT INTO `players` (`id`, `uuid`, `playername`) VALUES (NULL, ?, ?);");
  120.                         preparedStatementInfo.setString(1, uuid.toString());
  121.                         preparedStatementInfo.setString(2, name);
  122.                         preparedStatementInfo.executeUpdate();
  123.                     }
  124.                     String SELECT_QUERY = "SELECT `id`, `rank` FROM `players` WHERE `uuid` = ? LIMIT 1;";
  125.                     preparedStatement = Main.get().getDB().getConnection().get().prepareStatement(SELECT_QUERY);
  126.                     preparedStatement.setString(1, uuid.toString());
  127.                     resultSet = preparedStatement.executeQuery();
  128.                     if(resultSet != null && resultSet.next()) {
  129.                         accountId = resultSet.getInt(1);
  130.                         client.setRank(resultSet.getString("rank"));
  131.                     }
  132.                     client.setAccountId(accountId);
  133.                     lockMap.remove(name);
  134.                 }finally {
  135.                     if(preparedStatement != null)
  136.                         preparedStatement.close();
  137.                     if(preparedStatementInfo != null)
  138.                         preparedStatementInfo.close();
  139.                     if(resultSet != null)
  140.                         resultSet.close();                     
  141.                 }
  142.             }
  143.         }.writeOperation(Main.get().getDB().getExecutor(), Main.get().getLogger(), "Erro ao carregar dados de " + name);
  144.        
  145.         //Sleeps the thread with a timeout of 15s util loading Thread is finished.
  146.         while (lockMap.containsKey(client.getName()) && System.currentTimeMillis() - operationStart < 15000) {
  147.             try {
  148.                 Thread.sleep(2);
  149.             } catch (InterruptedException e) {
  150.                 e.printStackTrace();
  151.             }
  152.         }
  153.        
  154.         if(lockMap.containsKey(client.getName())) {
  155.             Main.get().getLogger().severe("SQL DEMOROU MUITO PARA RESPONDER.");
  156.         }
  157.        
  158.         return !lockMap.containsKey(client.getName());
  159.        
  160.     }
  161.    
  162.     public void flushAndDelete(UUID uuid) {
  163.         new SQLWriter() {
  164.             PreparedStatement preparedStatement = null;
  165.             @Override
  166.             public void onWrite() throws SQLException {
  167.                 String query = "UPDATE `players` WHERE `uuid` = ?;";
  168.                 try {
  169.                     preparedStatement = Main.get().getDB().getConnection().get().prepareStatement(query.toString());
  170.                     preparedStatement.setString(1, uuid.toString());
  171.                     preparedStatement.executeUpdate();
  172.                 }finally {
  173.                     delete(uuid);
  174.                 }
  175.             }
  176.            
  177.         }.writeOperation(Main.get().getDB().getExecutor(), Main.get().getLogger(), "Erro ao salvar client UUID " + uuid.toString());
  178.     }
  179.  
  180.     public Client addClient(UUID uuid) {
  181.         Client newClient = new Client(uuid);
  182.         Client oldClient = null;
  183.         synchronized (lock) {
  184.             oldClient = users.put(uuid, newClient);
  185.         }
  186.         if (oldClient != null) {
  187.             oldClient.close();
  188.         }
  189.         return newClient;
  190.     }
  191.  
  192.     public void delete(UUID uuid) {
  193.         synchronized (lock) {
  194.             if (users.containsKey(uuid)) {
  195.                 get(uuid).close();
  196.                 users.remove(uuid);
  197.             }
  198.         }
  199.     }
  200.  
  201.     public Client get(String name) {
  202.         synchronized (lock) {
  203.             return users.values().stream().filter(cur -> cur.getName().equalsIgnoreCase(name)).findFirst()
  204.                     .orElseGet(null);
  205.         }
  206.     }
  207.  
  208.     public Client get(UUID uuid) {
  209.         synchronized (lock) {
  210.             return users.get(uuid);
  211.         }
  212.     }
  213.  
  214.     public Client get(Player p) {
  215.         synchronized (lock) {
  216.             return users.get(p.getUniqueId());
  217.         }
  218.     }
  219.    
  220.     public Collection<Client> getClients() {
  221.         return users.values();
  222.     }
  223.    
  224. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top