Optimized queries to retrieve and update player information by removing inner join calls on the account.

Added account id retrieval on login.
Added account id caching in redis.
This commit is contained in:
Jonathan Williams 2015-03-25 15:10:59 -07:00
parent 294041b821
commit 6472194d44
69 changed files with 1585 additions and 238 deletions

View File

@ -224,6 +224,10 @@
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.PlayerCache/bin">
<include name="**/*.class"/>
</fileset>
<zipfileset src="../Libraries/commons-codec-1.6.jar" />
<zipfileset src="../Libraries/commons-io-2.4.jar" />
<zipfileset src="../Libraries/jedis-2.4.2.jar" />
@ -275,11 +279,11 @@
value="mineplex.bungee.BungeeRotator"/>
</manifest>
<zipfileset src="../Libraries/jooq-3.5.2.jar" />
<zipfileset src="../Libraries/httpclient-4.2.jar" />
<zipfileset src="../Libraries/httpcore-4.2.jar" />
<zipfileset src="../Libraries/httpclient-cache-4.2.jar" />
<zipfileset src="../Libraries/httpmime-4.2.jar" />
<zipfileset src="../Libraries/jooq-3.5.2.jar" />
<zipfileset src="../Libraries/gson-2.2.1.jar" />
<zipfileset src="../Libraries/commons-logging-1.1.1.jar" />
<zipfileset src="../Libraries/commons-codec-1.6.jar" />

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,7 @@
package mineplex.bungee.playerStats.data;
public class IpInfo
{
public int id;
public String ipAddress;
}

View File

@ -0,0 +1,17 @@
package mineplex.bungee;
public class IpInfo
{
public int id;
public String ipAddress;
public String countryCode;
public String countryName;
public String regionCode;
public String regionName;
public String city;
public String zipCode;
public String timeZone;
public double latitude;
public double longitude;
public int metroCode;
}

View File

@ -0,0 +1,146 @@
package mineplex.bungee;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class PlayerStatsRepository
{
private Connection _connection = null;
private String _connectionString = "jdbc:mysql://sqlstats.mineplex.com:3306/PlayerStats?autoReconnect=true&failOverReadOnly=false&maxReconnects=10&allowMultiQueries=true";
private String _userName = "root";
private String _password = "tAbechAk3wR7tuTh";
private static String SELECT_IPINFO = "SELECT id, ipAddress FROM ipInfo WHERE regionName IS NULL LIMIT 1000;";
private static String UPDATE_IPINFO = "UPDATE ipInfo SET countryCode = ?, countryName = ?, regionCode = ?, regionName = ?, city = ?, zipCode = ?, timeZone = ?, latitude = ?, longitude = ?, metroCode = ? WHERE id = ?;";
public void initialize()
{
try
{
if (_connection == null || _connection.isClosed())
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
catch (Exception exception)
{
exception.printStackTrace();
}
System.out.println("Initialized PlayerStats.");
}
public List<IpInfo> getIpAddresses()
{
List<IpInfo> ipinfos = new ArrayList<IpInfo>(1000);
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try
{
if (_connection == null || _connection.isClosed())
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
preparedStatement = _connection.prepareStatement(SELECT_IPINFO);
resultSet = preparedStatement.executeQuery();
while (resultSet.next())
{
IpInfo ipInfo = new IpInfo();
ipInfo.id = resultSet.getInt(1);
ipInfo.ipAddress = resultSet.getString(2);
ipinfos.add(ipInfo);
}
resultSet.close();
preparedStatement.close();
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (resultSet != null)
{
try
{
resultSet.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
return ipinfos;
}
public void updateIps(List<IpInfo> ips)
{
PreparedStatement preparedStatement = null;
try
{
if (_connection == null || _connection.isClosed())
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
preparedStatement = _connection.prepareStatement(UPDATE_IPINFO);
for (IpInfo ipInfo : ips)
{
preparedStatement.setString(1, ipInfo.countryCode);
preparedStatement.setString(2, ipInfo.countryName);
preparedStatement.setString(3, ipInfo.regionCode);
preparedStatement.setString(4, ipInfo.regionName);
preparedStatement.setString(5, ipInfo.city);
preparedStatement.setString(6, ipInfo.zipCode);
preparedStatement.setString(7, ipInfo.timeZone);
preparedStatement.setDouble(8, ipInfo.latitude);
preparedStatement.setDouble(9, ipInfo.longitude);
preparedStatement.setInt(10, ipInfo.metroCode);
preparedStatement.setInt(11, ipInfo.id);
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
}

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/gson-2.2.1.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/Mineplex.Core.Common"/>
<classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/httpclient-4.2.jar"/>
<classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/httpcore-4.2.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/Mineplex.ServerData"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_AFTER_CLEAN_TARGETS" value="ChestConverter,"/>
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_AUTO_TARGETS" value="ChestConverter,"/>
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_MANUAL_TARGETS" value="ChestConverter,"/>
<booleanAttribute key="org.eclipse.ant.ui.ATTR_TARGETS_UPDATED" value="true"/>
<booleanAttribute key="org.eclipse.ant.ui.DEFAULT_VM_INSTALL" value="false"/>
<booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/>
<stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.eclipse.ant.ui.AntClasspathProvider"/>
<booleanAttribute key="org.eclipse.jdt.launching.DEFAULT_CLASSPATH" value="true"/>
<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value=""/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${BUILD_FILES}/common.xml"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/Mineplex.ChestConverter}"/>
</launchConfiguration>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_AFTER_CLEAN_TARGETS" value="ServerMonitor,"/>
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_AUTO_TARGETS" value="ServerMonitor,"/>
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_MANUAL_TARGETS" value="ServerMonitor,"/>
<booleanAttribute key="org.eclipse.ant.ui.ATTR_TARGETS_UPDATED" value="true"/>
<booleanAttribute key="org.eclipse.ant.ui.DEFAULT_VM_INSTALL" value="false"/>
<stringAttribute key="org.eclipse.debug.core.ATTR_REFRESH_SCOPE" value="${project}"/>
<booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/>
<stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.eclipse.ant.ui.AntClasspathProvider"/>
<booleanAttribute key="org.eclipse.jdt.launching.DEFAULT_CLASSPATH" value="true"/>
<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value=""/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${BUILD_FILES}/common.xml"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/Mineplex.ServerMonitor}"/>
</launchConfiguration>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_AFTER_CLEAN_TARGETS" value="ServerMonitor,"/>
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_AUTO_TARGETS" value="ServerMonitor,"/>
<stringAttribute key="org.eclipse.ant.ui.ATTR_ANT_MANUAL_TARGETS" value="ServerMonitor,"/>
<booleanAttribute key="org.eclipse.ant.ui.ATTR_TARGETS_UPDATED" value="true"/>
<booleanAttribute key="org.eclipse.ant.ui.DEFAULT_VM_INSTALL" value="false"/>
<stringAttribute key="org.eclipse.debug.core.ATTR_REFRESH_SCOPE" value="${project}"/>
<booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/>
<stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.eclipse.ant.ui.AntClasspathProvider"/>
<booleanAttribute key="org.eclipse.jdt.launching.DEFAULT_CLASSPATH" value="true"/>
<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value=""/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${BUILD_FILES}/common.xml"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/Mineplex.ServerMonitor}"/>
</launchConfiguration>

View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Mineplex.ChestConverter</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
<triggers>auto,full,incremental,</triggers>
<arguments>
<dictionary>
<key>LaunchConfigHandle</key>
<value>&lt;project&gt;/.externalToolBuilders/ServerMonitor.launch</value>
</dictionary>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
<triggers>auto,full,incremental,</triggers>
<arguments>
<dictionary>
<key>LaunchConfigHandle</key>
<value>&lt;project&gt;/.externalToolBuilders/Chest.launch</value>
</dictionary>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.7

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="gson" level="project" />
<orderEntry type="library" name="httpclient" level="project" />
<orderEntry type="library" name="httpcore" level="project" />
<orderEntry type="module" module-name="Mineplex.Core.Common" />
<orderEntry type="module" module-name="Mineplex.ServerData" />
</component>
</module>

View File

@ -0,0 +1,46 @@
package mineplex.chestConverter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Logger;
public class ChestConverter
{
private static ChestConverterRepository _repository = null;
private static SimpleDateFormat _dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
public static void main (String args[])
{
_repository = new ChestConverterRepository();
int count = 5000;
while (true)
{
long time = System.currentTimeMillis();
HashMap<String, Integer> playerMap = _repository.retrieveKeyInventoryBatch(count);
if (playerMap.size() == 0)
return;
_repository.incrementClient(playerMap, false);
_repository.deleteKeys(count);
try
{
log("Natural sleep. " + count + " took " + (System.currentTimeMillis() - time) / 1000 + " seconds.");
Thread.sleep(250);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
break;
}
}
private static void log(String message)
{
System.out.println("[" + _dateFormat.format(new Date()) + "] " + message);
}
}

View File

@ -0,0 +1,316 @@
package mineplex.chestConverter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map.Entry;
public class ChestConverterRepository
{
private String _connectionString = "jdbc:mysql://db.mineplex.com:3306/Account";
private String _userName = "root";
private String _password = "tAbechAk3wR7tuTh";
private static String RETRIEVE_CHESTS = "SELECT A.uuid, count FROM accountInventory INNER JOIN accounts AS A ON A.id = accountInventory.accountId WHERE itemId = 56 AND count > 0 ORDER BY accountInventory.id LIMIT ?;";
private static String RETRIEVE_KEYS = "SELECT A.uuid, count FROM accountInventory INNER JOIN accounts AS A ON A.id = accountInventory.accountId WHERE itemId = 67 AND count > 0 ORDER BY accountInventory.id LIMIT ?;";
private static String DELETE_CHESTS = "DELETE FROM accountInventory WHERE itemId = 56 ORDER BY accountInventory.id LIMIT ?";
private static String DELETE_KEYS = "DELETE FROM accountInventory WHERE itemId = 67 ORDER BY accountInventory.id LIMIT ?";
private static String INSERT_CLIENT_INVENTORY = "INSERT INTO accountInventory (accountId, itemId, count) SELECT accounts.id, ?, ? FROM accounts WHERE accounts.uuid = ? ON DUPLICATE KEY UPDATE count=count + VALUES(count);";
private static String UPDATE_CLIENT_INVENTORY = "UPDATE accountInventory AS AI INNER JOIN accounts ON AI.accountId = accounts.id SET AI.count = AI.count + ? WHERE accounts.uuid = ? AND AI.itemId = ?;";
private static Connection _connection;
public ChestConverterRepository()
{
PreparedStatement preparedStatement = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
if (_connection == null || _connection.isClosed())
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
public HashMap<String, Integer> retrieveChestInventoryBatch(int count)
{
HashMap<String, Integer> playerList = new HashMap<String, Integer>();
PreparedStatement preparedStatement = null;
try
{
if (_connection == null || _connection.isClosed())
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
preparedStatement = _connection.prepareStatement(RETRIEVE_CHESTS);
preparedStatement.setInt(1, count);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next())
{
playerList.put(resultSet.getString(1), resultSet.getInt(2));
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
return playerList;
}
public HashMap<String, Integer> retrieveKeyInventoryBatch(int count)
{
HashMap<String, Integer> playerList = new HashMap<String, Integer>();
PreparedStatement preparedStatement = null;
try
{
if (_connection == null || _connection.isClosed())
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
preparedStatement = _connection.prepareStatement(RETRIEVE_KEYS);
preparedStatement.setInt(1, count);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next())
{
playerList.put(resultSet.getString(1), resultSet.getInt(2));
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
return playerList;
}
public void incrementClient(HashMap<String, Integer> playerList, boolean chest)
{
PreparedStatement preparedStatement = null;
try
{
if (_connection == null || _connection.isClosed())
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
preparedStatement = _connection.prepareStatement(UPDATE_CLIENT_INVENTORY);
for (Entry<String, Integer> entry : playerList.entrySet())
{
preparedStatement.setInt(1, entry.getValue());
preparedStatement.setString(2, entry.getKey());
preparedStatement.setInt(3, chest ? 690 : 692);
preparedStatement.addBatch();
if (chest)
{
if (entry.getValue() > 20)
{
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, entry.getKey());
preparedStatement.setInt(3, 692);
preparedStatement.addBatch();
}
if (entry.getValue() > 50)
{
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, entry.getKey());
preparedStatement.setInt(3, 691);
preparedStatement.addBatch();
}
}
}
int[] rowsAffected = preparedStatement.executeBatch();
int i = 0;
preparedStatement.close();
preparedStatement = _connection.prepareStatement(INSERT_CLIENT_INVENTORY);
for (Entry<String, Integer> entry : playerList.entrySet())
{
if (rowsAffected[i] < 1)
{
preparedStatement.setInt(1, chest ? 690 : 692);
preparedStatement.setInt(2, entry.getValue());
preparedStatement.setString(3, entry.getKey());
preparedStatement.addBatch();
if (chest)
{
if (entry.getValue() > 20)
{
preparedStatement.setInt(1, 692);
preparedStatement.setInt(2, 1);
preparedStatement.setString(3, entry.getKey());
preparedStatement.addBatch();
}
if (entry.getValue() > 50)
{
preparedStatement.setInt(1, 691);
preparedStatement.setInt(2, 1);
preparedStatement.setString(3, entry.getKey());
preparedStatement.addBatch();
}
}
}
i++;
}
preparedStatement.executeBatch();
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
public void deleteChests(int count)
{
PreparedStatement preparedStatement = null;
try
{
if (_connection == null || _connection.isClosed())
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
preparedStatement = _connection.prepareStatement(DELETE_CHESTS);
preparedStatement.setInt(1, count);
preparedStatement.executeUpdate();
System.out.println("Deleting " + count + " inventory records.");
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
public void deleteKeys(int count)
{
PreparedStatement preparedStatement = null;
try
{
if (_connection == null || _connection.isClosed())
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
preparedStatement = _connection.prepareStatement(DELETE_KEYS);
preparedStatement.setInt(1, count);
preparedStatement.executeUpdate();
System.out.println("Deleting " + count + " inventory records.");
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
}

View File

@ -0,0 +1,6 @@
package mineplex.chestConverter;
public interface GenericRunnable<T>
{
void run(T t);
}

View File

@ -0,0 +1,33 @@
package mineplex.core.account;
import java.util.UUID;
import mineplex.serverdata.data.Data;
public class AccountCache implements Data
{
private UUID _uuid;
private Integer _id;
public AccountCache(UUID uuid, int id)
{
_uuid = uuid;
_id = id;
}
public UUID getUUID()
{
return _uuid;
}
public int getId()
{
return _id;
}
@Override
public String getDataId()
{
return _uuid.toString();
}
}

View File

@ -6,7 +6,7 @@ import org.bukkit.entity.Player;
public class CoreClient
{
private int _accountId;
private int _accountId = -1;
private String _name;
private Player _player;
private Rank _rank;
@ -37,7 +37,7 @@ public class CoreClient
_player = player;
}
public int GetAccountId()
public int getAccountId()
{
return _accountId;
}
@ -48,7 +48,7 @@ public class CoreClient
_player = null;
}
public void SetAccountId(int accountId)
public void setAccountId(int accountId)
{
_accountId = accountId;
}

View File

@ -21,6 +21,10 @@ import mineplex.core.common.util.UtilPlayer;
import mineplex.core.timing.TimingManager;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.serverdata.Region;
import mineplex.serverdata.data.BungeeServer;
import mineplex.serverdata.redis.RedisDataRepository;
import mineplex.serverdata.servers.ServerManager;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
@ -43,6 +47,7 @@ public class CoreClientManager extends MiniPlugin
private AccountRepository _repository;
private NautHashMap<String, CoreClient> _clientList;
private HashSet<String> _duplicateLoginGlitchPreventionList;
private RedisDataRepository<AccountCache> _accountCacheRepository;
private NautHashMap<String, ILoginProcessor> _loginProcessors = new NautHashMap<String, ILoginProcessor>();
@ -59,6 +64,9 @@ public class CoreClientManager extends MiniPlugin
_repository = new AccountRepository(plugin, webServer);
_clientList = new NautHashMap<String, CoreClient>();
_duplicateLoginGlitchPreventionList = new HashSet<String>();
_accountCacheRepository = new RedisDataRepository<AccountCache>(ServerManager.getMasterConnection(), ServerManager.getSlaveConnection(),
Region.ALL, AccountCache.class, "accountCache");
}
public AccountRepository getRepository()
@ -155,7 +163,7 @@ public class CoreClientManager extends MiniPlugin
catch(Exception exception)
{
event.disallow(Result.KICK_OTHER, "Error retrieving information from web, please retry in a minute.");
System.out.println(exception.getMessage());
exception.printStackTrace();
}
finally
{
@ -189,34 +197,47 @@ public class CoreClientManager extends MiniPlugin
{
public void run()
{
ClientToken token = null;
Gson gson = new Gson();
// Fails if not in DB and if duplicate.
UUID uuid = loadUUIDFromDB(playerName);
if (uuid == null)
uuid = UUIDFetcher.getUUIDOf(playerName);
String response = _repository.getClientByUUID(uuid);
token = gson.fromJson(response, ClientToken.class);
client.SetAccountId(token.AccountId);
client.SetRank(Rank.valueOf(token.Rank));
_repository.login(_loginProcessors, uuid.toString(), client.GetPlayerName());
// JSON sql response
Bukkit.getServer().getPluginManager().callEvent(new ClientWebResponseEvent(response, uuid));
Bukkit.getServer().getScheduler().runTask(getPlugin(), new Runnable()
try
{
public void run()
ClientToken token = null;
Gson gson = new Gson();
// Fails if not in DB and if duplicate.
UUID uuid = loadUUIDFromDB(playerName);
if (uuid == null)
uuid = UUIDFetcher.getUUIDOf(playerName);
String response = _repository.getClientByUUID(uuid);
token = gson.fromJson(response, ClientToken.class);
client.SetRank(Rank.valueOf(token.Rank));
client.setAccountId(_repository.login(_loginProcessors, uuid.toString(), client.GetPlayerName()));
// JSON sql response
Bukkit.getServer().getPluginManager().callEvent(new ClientWebResponseEvent(response, uuid));
if (client.getAccountId() > 0)
_accountCacheRepository.addElement(new AccountCache(uuid, client.getAccountId()));
Bukkit.getServer().getScheduler().runTask(getPlugin(), new Runnable()
{
if (runnable != null)
runnable.run();
}
});
public void run()
{
if (runnable != null)
runnable.run();
}
});
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
runnable.run();
}
}
});
}
@ -234,7 +255,7 @@ public class CoreClientManager extends MiniPlugin
{
public void run()
{
_repository.login(_loginProcessors, uuid.toString(), client.GetPlayerName());
client.setAccountId(_repository.login(_loginProcessors, uuid.toString(), client.GetPlayerName()));
_clientLoginLock.remove(client.GetPlayerName());
}
});
@ -244,8 +265,7 @@ public class CoreClientManager extends MiniPlugin
TimingManager.stop(client.GetPlayerName() + " GetClient.");
token = gson.fromJson(response, ClientToken.class);
client.SetAccountId(token.AccountId);
client.SetRank(Rank.valueOf(token.Rank));
// _repository.updateMysqlRank(uuid.toString(), token.Rank, token.RankPerm, new Timestamp(Date.parse(token.RankExpire)).toString());
@ -272,6 +292,11 @@ public class CoreClientManager extends MiniPlugin
TimingManager.stop(client.GetPlayerName() + " LoadClient Total.");
System.out.println(client.GetPlayerName() + "'s account id = " + client.getAccountId());
if (client.getAccountId() > 0)
_accountCacheRepository.addElement(new AccountCache(uuid, client.getAccountId()));
return !_clientLoginLock.containsKey(client.GetPlayerName());
}
@ -473,4 +498,9 @@ public class CoreClientManager extends MiniPlugin
return client.GetRank().Has(rank);
}
public int getCachedClientAccountId(UUID uuid)
{
return _accountCacheRepository.getElement(uuid.toString()).getId();
}
}

View File

@ -9,5 +9,5 @@ public interface ILoginProcessor
void processLoginResultSet(String playerName, ResultSet resultSet) throws SQLException;
String getQuery(String uuid, String name);
String getQuery(int accountId, String uuid, String name);
}

View File

@ -19,7 +19,6 @@ import mineplex.core.account.repository.token.RankUpdateToken;
import mineplex.core.common.Rank;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.common.util.UUIDFetcher;
import mineplex.core.database.DBPool;
import mineplex.core.database.DatabaseRunnable;
import mineplex.core.database.RepositoryBase;
@ -32,7 +31,7 @@ import mineplex.core.server.remotecall.JsonWebCall;
public class AccountRepository extends RepositoryBase
{
private static String CREATE_ACCOUNT_TABLE = "CREATE TABLE IF NOT EXISTS accounts (id INT NOT NULL AUTO_INCREMENT, uuid VARCHAR(100), name VARCHAR(40), gems INT, rank VARCHAR(40), rankPerm BOOL, rankExpire LONG, lastLogin LONG, totalPlayTime LONG, PRIMARY KEY (id), UNIQUE INDEX uuidIndex (uuid), UNIQUE INDEX nameIndex (name), INDEX rankIndex (rank));";
private static String ACCOUNT_LOGIN_NEW = "INSERT INTO accounts (uuid, name, lastLogin) values(?, ?, now()) ON DUPLICATE KEY UPDATE name=VALUES(name), lastLogin=VALUES(lastLogin);";
private static String ACCOUNT_LOGIN_NEW = "INSERT INTO accounts (uuid, name, lastLogin) values(?, ?, now());";
private static String UPDATE_ACCOUNT_RANK = "UPDATE accounts SET rank=?, rankPerm=false, rankExpire=now() + INTERVAL 1 MONTH WHERE uuid = ?;";
private static String UPDATE_ACCOUNT_RANK_DONOR = "UPDATE accounts SET rank=?, donorRank=?, rankPerm=false, rankExpire=now() + INTERVAL 1 MONTH WHERE uuid = ?;";
private static String UPDATE_ACCOUNT_RANK_PERM = "UPDATE accounts SET rank=?, rankPerm=true WHERE uuid = ?;";
@ -56,13 +55,41 @@ public class AccountRepository extends RepositoryBase
//executeUpdate(CREATE_ACCOUNT_TABLE);
}
public void login(NautHashMap<String, ILoginProcessor> loginProcessors, String uuid, String name)
public int login(NautHashMap<String, ILoginProcessor> loginProcessors, String uuid, String name)
{
int accountId = -1;
try (
Connection connection = getConnection();
Statement statement = connection.createStatement()
)
{
statement.execute("SELECT id FROM accounts WHERE accounts.uuid = '" + uuid + "' LIMIT 1;");
ResultSet resultSet = statement.getResultSet();
while (resultSet.next())
{
accountId = resultSet.getInt(1);
}
if (accountId == -1)
{
final List<Integer> tempList = new ArrayList<Integer>(1);
executeInsert(ACCOUNT_LOGIN_NEW, new ResultSetCallable()
{
@Override
public void processResultSet(ResultSet resultSet) throws SQLException
{
while (resultSet.next())
{
tempList.add(resultSet.getInt(1));
}
}
},new ColumnVarChar("uuid", 100, uuid), new ColumnVarChar("name", 100, name));
accountId = tempList.get(0);
}
/*
boolean statementStatus = statement.execute(
"UPDATE accounts SET name='" + name + "', lastLogin=now() WHERE accounts.uuid = '" + uuid + "';"
@ -75,10 +102,11 @@ public class AccountRepository extends RepositoryBase
);
*/
String loginString = "UPDATE accounts SET name='" + name + "', lastLogin=now() WHERE accounts.uuid = '" + uuid + "';";
String loginString = "UPDATE accounts SET name='" + name + "', lastLogin=now() WHERE id = '" + accountId + "';";
for (ILoginProcessor loginProcessor : loginProcessors.values())
{
loginString += loginProcessor.getQuery(uuid, name);
loginString += loginProcessor.getQuery(accountId, uuid, name);
}
statement.execute(loginString);
@ -108,25 +136,22 @@ public class AccountRepository extends RepositoryBase
System.out.println("Done");
*/
boolean accountExists = statement.getUpdateCount() != 0;
statement.getUpdateCount();
statement.getMoreResults();
for (ILoginProcessor loginProcessor : loginProcessors.values())
{
loginProcessor.processLoginResultSet(name, statement.getResultSet());
statement.getMoreResults();
}
if (!accountExists)
{
executeUpdate(ACCOUNT_LOGIN_NEW, new ColumnVarChar("uuid", 100, uuid), new ColumnVarChar("name", 100, name));
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
return accountId;
}
public String GetClient(String name, UUID uuid, String ipAddress)

View File

@ -78,8 +78,8 @@ public class BenefitManager extends MiniDbClientPlugin<BenefitData>
}
@Override
public String getQuery(String uuid, String name)
public String getQuery(int accountId, String uuid, String name)
{
return "SELECT benefit FROM rankBenefits WHERE rankBenefits.uuid = '" + uuid + "';";
return "SELECT benefit FROM rankBenefits WHERE rankBenefits.accountId = '" + accountId + "';";
}
}

View File

@ -11,7 +11,7 @@ import org.bukkit.plugin.java.JavaPlugin;
public class BenefitManagerRepository extends RepositoryBase
{
// private static String CREATE_BENEFIT_TABLE = "CREATE TABLE IF NOT EXISTS rankBenefits (id INT NOT NULL AUTO_INCREMENT, uuid VARCHAR(100), benefit VARCHAR(100), PRIMARY KEY (id), INDEX rankUuid (uuid));";
private static String CREATE_BENEFIT_TABLE = "CREATE TABLE IF NOT EXISTS rankBenefits (id INT NOT NULL AUTO_INCREMENT, accountId INT, benefit VARCHAR(100), PRIMARY KEY (id), INDEX rankUuid (uuid));";
private static String INSERT_BENEFIT = "INSERT INTO rankBenefits (uuid, benefit) VALUES (?, ?);";

View File

@ -116,7 +116,7 @@ public abstract class RepositoryBase implements Listener
}
catch (SQLException exception)
{
executeInsert(query, callable, columns);
exception.printStackTrace();
}
catch (Exception exception)
{
@ -142,7 +142,7 @@ public abstract class RepositoryBase implements Listener
}
catch (SQLException exception)
{
executeQuery(statement, callable, columns);
exception.printStackTrace();
}
catch (Exception exception)
{
@ -162,7 +162,7 @@ public abstract class RepositoryBase implements Listener
}
catch (SQLException exception)
{
executeQuery(query, callable, columns);
exception.printStackTrace();
}
catch (Exception exception)
{

View File

@ -4,6 +4,7 @@ import java.util.UUID;
import org.bukkit.entity.Player;
import mineplex.core.account.CoreClient;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.Callback;
@ -27,34 +28,39 @@ public class CoinCommand extends CommandBase<DonationManager>
return;
}
String targetName = args[0];
String coinsString = args[1];
final String targetName = args[0];
final String coinsString = args[1];
Player target = UtilPlayer.searchExact(targetName);
if (target == null)
{
UUID uuid = UUIDFetcher.getUUIDOf(targetName);
if (uuid != null)
Plugin.getClientManager().loadClientByName(targetName, new Runnable()
{
rewardCoins(caller, null, targetName, uuid, coinsString);
}
else
{
UtilPlayer.message(caller, F.main("Coin", "Could not find player " + F.name(targetName)));
}
public void run()
{
CoreClient client = Plugin.getClientManager().Get(targetName);
if (client != null)
rewardCoins(caller, null, targetName, client.getAccountId(), coinsString);
else
{
UtilPlayer.message(caller, F.main("Coin", "Could not find player " + F.name(targetName)));
}
}
});
}
else
{
rewardCoins(caller, target, target.getName(), target.getUniqueId(), coinsString);
rewardCoins(caller, target, target.getName(), Plugin.getClientManager().Get(target).getAccountId(), coinsString);
}
}
private void rewardCoins(final Player caller, final Player target, final String targetName, final UUID uuid, String coinsString)
private void rewardCoins(final Player caller, final Player target, final String targetName, final int accountId, String coinsString)
{
try
{
int coins = Integer.parseInt(coinsString);
rewardCoins(caller, target, targetName, uuid, coins);
rewardCoins(caller, target, targetName, accountId, coins);
}
catch (Exception e)
{
@ -62,7 +68,7 @@ public class CoinCommand extends CommandBase<DonationManager>
}
}
private void rewardCoins(final Player caller, final Player target, final String targetName, final UUID uuid, final int coins)
private void rewardCoins(final Player caller, final Player target, final String targetName, final int accountId, final int coins)
{
Plugin.RewardCoins(new Callback<Boolean>()
{
@ -75,6 +81,6 @@ public class CoinCommand extends CommandBase<DonationManager>
UtilPlayer.message(target, F.main("Coin", F.name(caller.getName()) + " gave you " + F.elem(coins + " Coins") + "."));
}
}
}, caller.getName(), targetName, uuid, coins);
}, caller.getName(), targetName, accountId, coins);
}
}

View File

@ -58,7 +58,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
//_repository.updateGemsAndCoins(uuid, Get(token.Name).GetGems(), Get(token.Name).getCoins());
}
public void PurchaseUnknownSalesPackage(final Callback<TransactionResponse> callback, final String name, final UUID uuid, final String packageName, final boolean coinPurchase, final int cost, boolean oneTimePurchase)
public void PurchaseUnknownSalesPackage(final Callback<TransactionResponse> callback, final String name, final int accountId, final String packageName, final boolean coinPurchase, final int cost, boolean oneTimePurchase)
{
final Donor donor = Bukkit.getPlayerExact(name) != null ? Get(name) : null;
@ -89,7 +89,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
if (callback != null)
callback.run(response);
}
}, name, uuid.toString(), packageName, coinPurchase, cost);
}, name, accountId, packageName, coinPurchase, cost);
}
public void PurchaseKnownSalesPackage(final Callback<TransactionResponse> callback, final String name, final UUID uuid, final int cost, final int salesPackageId)
@ -196,12 +196,12 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
_gemQueue.clear();
}
public void RewardCoins(Callback<Boolean> callback, String caller, String name, UUID uuid, int amount)
public void RewardCoins(Callback<Boolean> callback, String caller, String name, int accountId, int amount)
{
RewardCoins(callback, caller, name, uuid, amount, true);
RewardCoins(callback, caller, name, accountId, amount, true);
}
public void RewardCoins(final Callback<Boolean> callback, final String caller, final String name, final UUID uuid, final int amount, final boolean updateTotal)
public void RewardCoins(final Callback<Boolean> callback, final String caller, final String name, final int accountId, final int amount, final boolean updateTotal)
{
_repository.rewardCoins(new Callback<Boolean>()
{
@ -223,7 +223,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
callback.run(true);
}
}
}, caller, name, uuid.toString(), amount);
}, caller, name, accountId, amount);
}
public void RewardCoinsLater(final String caller, final Player player, final int amount)
@ -266,7 +266,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
continue;
//Actually Add Gems
RewardCoins(null, caller, player.getName(), player.getUniqueId(), total, false);
RewardCoins(null, caller, player.getName(), ClientManager.Get(player).getAccountId(), total, false);
System.out.println("Queue Added [" + player + "] with Coins [" + total + "] for [" + caller + "]");
@ -278,12 +278,12 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
_coinQueue.clear();
}
public void RewardGold(Callback<Boolean> callback, String caller, String name, UUID uuid, int amount)
public void RewardGold(Callback<Boolean> callback, String caller, String name, int accountId, int amount)
{
RewardGold(callback, caller, name, uuid, amount, true);
RewardGold(callback, caller, name, accountId, amount, true);
}
public void RewardGold(final Callback<Boolean> callback, final String caller, final String name, final UUID uuid, final int amount, final boolean updateTotal)
public void RewardGold(final Callback<Boolean> callback, final String caller, final String name, final int accountId, final int amount, final boolean updateTotal)
{
_repository.rewardGold(new Callback<Boolean>()
{
@ -309,7 +309,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
if (callback != null)
callback.run(true);
}
}, caller, name, uuid.toString(), amount);
}, caller, name, accountId, amount);
}
public void RewardGoldLater(final String caller, final Player player, final int amount)
@ -352,7 +352,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
continue;
//Actually Add Gold
RewardGold(null, caller, player.getName(), player.getUniqueId(), total, false);
RewardGold(null, caller, player.getName(), ClientManager.Get(player).getAccountId(), total, false);
System.out.println("Queue Added [" + player + "] with Gold [" + total + "] for [" + caller + "]");
@ -375,15 +375,15 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
Get(playerName).addGold(_repository.retrieveDonorInfo(resultSet).getGold());
}
@Override
public String getQuery(String uuid, String name)
{
return "SELECT gold FROM accounts WHERE uuid = '" + uuid + "';";
}
@Override
protected Donor AddPlayer(String player)
{
return new Donor();
}
@Override
public String getQuery(int accountId, String uuid, String name)
{
return "SELECT gold FROM accounts WHERE id = '" + accountId + "';";
}
}

View File

@ -4,6 +4,7 @@ import java.util.UUID;
import org.bukkit.entity.Player;
import mineplex.core.account.CoreClient;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.Callback;
@ -31,34 +32,39 @@ public class GoldCommand extends CommandBase<DonationManager>
return;
}
String targetName = args[0];
String goldString = args[1];
final String targetName = args[0];
final String goldString = args[1];
Player target = UtilPlayer.searchExact(targetName);
if (target == null)
{
UUID uuid = UUIDFetcher.getUUIDOf(targetName);
if (uuid != null)
Plugin.getClientManager().loadClientByName(targetName, new Runnable()
{
rewardGold(caller, null, targetName, uuid, goldString);
}
else
{
UtilPlayer.message(caller, F.main("Gold", "Could not find player " + F.name(targetName)));
}
public void run()
{
CoreClient client = Plugin.getClientManager().Get(targetName);
if (client != null)
rewardGold(caller, null, targetName, client.getAccountId(), goldString);
else
{
UtilPlayer.message(caller, F.main("Gold", "Could not find player " + F.name(targetName)));
}
}
});
}
else
{
rewardGold(caller, target, target.getName(), target.getUniqueId(), goldString);
rewardGold(caller, target, target.getName(), Plugin.getClientManager().Get(target).getAccountId(), goldString);
}
}
private void rewardGold(final Player caller, final Player target, final String targetName, final UUID uuid, String goldString)
private void rewardGold(final Player caller, final Player target, final String targetName, final int accountId, String goldString)
{
try
{
int gold = Integer.parseInt(goldString);
rewardGold(caller, target, targetName, uuid, gold);
rewardGold(caller, target, targetName, accountId, gold);
}
catch (Exception e)
{
@ -66,7 +72,7 @@ public class GoldCommand extends CommandBase<DonationManager>
}
}
private void rewardGold(final Player caller, final Player target, final String targetName, final UUID uuid, final int gold)
private void rewardGold(final Player caller, final Player target, final String targetName, final int accountId, final int gold)
{
Plugin.RewardGold(new Callback<Boolean>()
{
@ -79,6 +85,6 @@ public class GoldCommand extends CommandBase<DonationManager>
UtilPlayer.message(target, F.main("Gold", F.name(caller.getName()) + " gave you " + F.elem(gold + " Gold") + "."));
}
}
}, caller.getName(), targetName, uuid, gold);
}, caller.getName(), targetName, accountId, gold);
}
}

View File

@ -2,7 +2,6 @@ package mineplex.core.donation.repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
@ -23,12 +22,12 @@ import mineplex.core.server.util.TransactionResponse;
public class DonationRepository extends RepositoryBase
{
private static String CREATE_COIN_TRANSACTION_TABLE = "CREATE TABLE IF NOT EXISTS accountCoinTransactions (id INT NOT NULL AUTO_INCREMENT, accounts_uuid VARCHAR(100), reason VARCHAR(100), coins INT, PRIMARY KEY (id), FOREIGN KEY (accounts_uuid) REFERENCES accounts(uuid), INDEX coinUuidIndex (accounts_uuid));";
private static String CREATE_GEM_TRANSACTION_TABLE = "CREATE TABLE IF NOT EXISTS accountGemTransactions (id INT NOT NULL AUTO_INCREMENT, accounts_uuid VARCHAR(100), reason VARCHAR(100), gems INT, PRIMARY KEY (id), FOREIGN KEY (accounts_uuid) REFERENCES accounts(uuid), INDEX gemUuidIndex (accounts_uuid));";
private static String INSERT_COIN_TRANSACTION = "INSERT INTO accountCoinTransactions(accounts_uuid, reason, coins) VALUES(?, ?, ?);";
private static String UPDATE_ACCOUNT_COINS = "UPDATE accounts SET coins = coins + ? WHERE uuid = ?;";
private static String UPDATE_ACCOUNT_GOLD = "UPDATE accounts SET gold = gold + ? WHERE uuid = ?;";
private static String UPDATE_NULL_ACCOUNT_GEMS_AND_COINS_ = "UPDATE accounts SET gems = ?, coins = ? WHERE uuid = ? AND gems IS NULL AND coins IS NULL;";
private static String CREATE_COIN_TRANSACTION_TABLE = "CREATE TABLE IF NOT EXISTS accountCoinTransactions (id INT NOT NULL AUTO_INCREMENT, accountId INT, reason VARCHAR(100), coins INT, PRIMARY KEY (id), FOREIGN KEY (accountId) REFERENCES accounts(id));";
private static String CREATE_GEM_TRANSACTION_TABLE = "CREATE TABLE IF NOT EXISTS accountGemTransactions (id INT NOT NULL AUTO_INCREMENT, accountId INT, reason VARCHAR(100), gems INT, PRIMARY KEY (id), FOREIGN KEY (accountId) REFERENCES accounts(id));";
private static String INSERT_COIN_TRANSACTION = "INSERT INTO accountCoinTransactions(accountId, reason, coins) VALUES(?, ?, ?);";
private static String UPDATE_ACCOUNT_COINS = "UPDATE accounts SET coins = coins + ? WHERE id = ?;";
private static String UPDATE_ACCOUNT_GOLD = "UPDATE accounts SET gold = gold + ? WHERE id = ?;";
private static String UPDATE_NULL_ACCOUNT_GEMS_AND_COINS_ = "UPDATE accounts SET gems = ?, coins = ? WHERE id = ? AND gems IS NULL AND coins IS NULL;";
private String _webAddress;
@ -70,7 +69,7 @@ public class DonationRepository extends RepositoryBase
}), "Error purchasing known sales package in DonationRepository : ");
}
public void PurchaseUnknownSalesPackage(final Callback<TransactionResponse> callback, final String name, final String uuid, final String packageName, final boolean coinPurchase, final int cost)
public void PurchaseUnknownSalesPackage(final Callback<TransactionResponse> callback, final String name, final int accountId, final String packageName, final boolean coinPurchase, final int cost)
{
final UnknownPurchaseToken token = new UnknownPurchaseToken();
token.AccountName = name;
@ -87,8 +86,8 @@ public class DonationRepository extends RepositoryBase
{
if (coinPurchase)
{
executeUpdate(UPDATE_ACCOUNT_COINS, new ColumnInt("coins", -cost), new ColumnVarChar("uuid", 100, uuid));
executeUpdate(INSERT_COIN_TRANSACTION, new ColumnVarChar("uuid", 100, uuid), new ColumnVarChar("reason", 100, "Purchased " + packageName), new ColumnInt("coins", -cost));
executeUpdate(UPDATE_ACCOUNT_COINS, new ColumnInt("coins", -cost), new ColumnInt("id", accountId));
//executeUpdate(INSERT_COIN_TRANSACTION, new ColumnInt("id", accountId), new ColumnVarChar("reason", 100, "Purchased " + packageName), new ColumnInt("coins", -cost));
}
}
@ -143,7 +142,7 @@ public class DonationRepository extends RepositoryBase
}), "Error updating player gem amount in DonationRepository : ");
}
public void rewardCoins(final Callback<Boolean> callback, final String giver, String name, final String uuid, final int coins)
public void rewardCoins(final Callback<Boolean> callback, final String giver, String name, final int accountId, final int coins)
{
final GemRewardToken token = new GemRewardToken();
token.Source = giver;
@ -156,8 +155,8 @@ public class DonationRepository extends RepositoryBase
{
if (response)
{
executeUpdate(UPDATE_ACCOUNT_COINS, new ColumnInt("coins", coins), new ColumnVarChar("uuid", 100, uuid));
executeUpdate(INSERT_COIN_TRANSACTION, new ColumnVarChar("uuid", 100, uuid), new ColumnVarChar("reason", 100, "Rewarded by " + giver), new ColumnInt("coins", coins));
executeUpdate(UPDATE_ACCOUNT_COINS, new ColumnInt("coins", coins), new ColumnInt("id", accountId));
//executeUpdate(INSERT_COIN_TRANSACTION, new ColumnInt("id", accountId), new ColumnVarChar("reason", 100, "Rewarded by " + giver), new ColumnInt("coins", coins));
}
Bukkit.getServer().getScheduler().runTask(Plugin, new Runnable()
@ -180,13 +179,13 @@ public class DonationRepository extends RepositoryBase
}), "Error updating player coin amount in DonationRepository : ");
}
public void rewardGold(final Callback<Boolean> callback, final String giver, final String name, final String uuid, final int gold)
public void rewardGold(final Callback<Boolean> callback, final String giver, final String name, final int accountId, final int gold)
{
handleDatabaseCall(new DatabaseRunnable(new Runnable()
{
public void run()
{
if (executeUpdate(UPDATE_ACCOUNT_GOLD, new ColumnInt("gold", gold), new ColumnVarChar("uuid", 100, uuid)) < 1)
if (executeUpdate(UPDATE_ACCOUNT_GOLD, new ColumnInt("gold", gold), new ColumnInt("id", accountId)) < 1)
{
callback.run(false);
}
@ -208,13 +207,13 @@ public class DonationRepository extends RepositoryBase
{
}
public void updateGemsAndCoins(final UUID uuid, final int gems, final int coins)
public void updateGemsAndCoins(final int accountId, final int gems, final int coins)
{
handleDatabaseCall(new DatabaseRunnable(new Runnable()
{
public void run()
{
executeUpdate(UPDATE_NULL_ACCOUNT_GEMS_AND_COINS_, new ColumnInt("gems", gems), new ColumnInt("coins", coins), new ColumnVarChar("uuid", 100, uuid.toString()));
executeUpdate(UPDATE_NULL_ACCOUNT_GEMS_AND_COINS_, new ColumnInt("gems", gems), new ColumnInt("coins", coins), new ColumnInt("id", accountId));
}
}), "Error updating player's null gems and coins DonationRepository : ");
}

View File

@ -114,7 +114,7 @@ public class EloManager extends MiniDbClientPlugin<EloClientData>
}
@Override
public String getQuery(String uuid, String name)
public String getQuery(int accountId, String uuid, String name)
{
return "SELECT gameType, elo FROM eloRating WHERE uuid = '" + uuid + "';";
}

View File

@ -418,7 +418,7 @@ public class FriendManager extends MiniDbClientPlugin<FriendData>
}
@Override
public String getQuery(String uuid, String name)
public String getQuery(int accountId, String uuid, String name)
{
return "SELECT tA.Name, status, tA.lastLogin, now() FROM accountFriend INNER Join accounts AS fA ON fA.uuid = uuidSource INNER JOIN accounts AS tA ON tA.uuid = uuidTarget WHERE uuidSource = '"
+ uuid + "';";

View File

@ -0,0 +1,24 @@
package mineplex.core.friend.redis;
import mineplex.serverdata.commands.ServerCommand;
public class DeleteFriend extends ServerCommand
{
private String _deleter;
private String _deleted;
public String getDeleter() { return _deleter; }
public String getDeleted() { return _deleted; }
public DeleteFriend(String deleter, String deleted)
{
_deleter = deleter;
_deleted = deleted;
}
@Override
public void run()
{
// Utilitizes a callback functionality to seperate dependencies
}
}

View File

@ -0,0 +1,6 @@
package mineplex.core.friend.redis;
public class DeleteFriendHandler
{
}

View File

@ -0,0 +1,24 @@
package mineplex.core.friend.redis;
import mineplex.serverdata.commands.ServerCommand;
public class FriendRequest extends ServerCommand
{
private String _requester;
private String _requested;
public String getRequester() { return _requester; }
public String getRequested() { return _requested; }
public FriendRequest(String requester, String requested)
{
_requester = requester;
_requested = requested;
}
@Override
public void run()
{
// Utilitizes a callback functionality to seperate dependencies
}
}

View File

@ -0,0 +1,6 @@
package mineplex.core.friend.redis;
public class FriendRequestHandler
{
}

View File

@ -236,7 +236,7 @@ public class IgnoreManager extends MiniDbClientPlugin<IgnoreData>
}
@Override
public String getQuery(String uuid, String name)
public String getQuery(int accountId, String uuid, String name)
{
return "SELECT tA.Name FROM accountIgnore INNER Join accounts AS fA ON fA.uuid = uuidIgnorer INNER JOIN accounts AS tA ON tA.uuid = uuidIgnored LEFT JOIN playerMap ON tA.name = playerName WHERE uuidIgnorer = '"
+ uuid + "';";

View File

@ -4,6 +4,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@ -114,7 +115,7 @@ public class InventoryManager extends MiniDbClientPlugin<ClientInventory>
if (callback != null)
callback.run(success);
}
}, player.getUniqueId().toString(), category, item, count);
}, player.getUniqueId(), category, item, count);
}
@ -149,7 +150,7 @@ public class InventoryManager extends MiniDbClientPlugin<ClientInventory>
return item;
}
public void addItemToInventoryForOffline(final Callback<Boolean> callback, final String uuidString, final String category, final String item, final int count)
public void addItemToInventoryForOffline(final Callback<Boolean> callback, final UUID uuid, final String category, final String item, final int count)
{
Bukkit.getServer().getScheduler().runTaskAsynchronously(getPlugin(), new Runnable()
{
@ -179,7 +180,7 @@ public class InventoryManager extends MiniDbClientPlugin<ClientInventory>
synchronized (_inventoryLock)
{
final boolean success = _repository.incrementClientInventoryItem(uuidString, _items.get(item).Id, count);
final boolean success = _repository.incrementClientInventoryItem(ClientManager.getCachedClientAccountId(uuid), _items.get(item).Id, count);
if (callback != null)
{
@ -224,7 +225,7 @@ public class InventoryManager extends MiniDbClientPlugin<ClientInventory>
}
}
}
}, player.getUniqueId().toString(), category, item, count);
}, player.getUniqueId(), category, item, count);
}
}
@ -256,8 +257,8 @@ public class InventoryManager extends MiniDbClientPlugin<ClientInventory>
}
@Override
public String getQuery(String uuid, String name)
public String getQuery(int accountId, String uuid, String name)
{
return "SELECT items.name, ic.name as category, count FROM accountInventory AS ai INNER JOIN items ON items.id = ai.itemId INNER JOIN itemCategories AS ic ON ic.id = items.categoryId INNER JOIN accounts ON accounts.id = ai.accountId WHERE accounts.uuid = '" + uuid + "';";
return "SELECT items.name, ic.name as category, count FROM accountInventory AS ai INNER JOIN items ON items.id = ai.itemId INNER JOIN itemCategories AS ic ON ic.id = items.categoryId WHERE ai.accountId = '" + accountId + "';";
}
}

View File

@ -4,6 +4,7 @@ import java.util.UUID;
import org.bukkit.entity.Player;
import mineplex.core.account.CoreClient;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.Callback;
@ -44,7 +45,7 @@ public class GiveItemCommand extends CommandBase<InventoryManager>
final String itemName = itemNameTemp;
Item item = Plugin.getItem(itemName);
final Item item = Plugin.getItem(itemName);
Player player = UtilPlayer.searchExact(playerName);
if (item == null)
@ -59,21 +60,28 @@ public class GiveItemCommand extends CommandBase<InventoryManager>
}
else
{
UUID uuid = UUIDFetcher.getUUIDOf(playerName);
if (uuid != null)
Plugin.getClientManager().loadClientByName(playerName, new Runnable()
{
Plugin.addItemToInventoryForOffline(new Callback<Boolean>()
public void run()
{
public void run (Boolean success)
UUID uuid = Plugin.getClientManager().loadUUIDFromDB(playerName);
if (uuid != null)
{
UtilPlayer.message(caller, F.main("Item", "You gave " + F.elem(amount + " " + itemName) + " to offline player " + F.name(playerName)));
Plugin.addItemToInventoryForOffline(new Callback<Boolean>()
{
public void run (Boolean success)
{
UtilPlayer.message(caller, F.main("Item", "You gave " + F.elem(amount + " " + itemName) + " to offline player " + F.name(playerName)));
}
}, uuid, item.Category, item.Name, amount);
}
}, uuid.toString(), item.Category, item.Name, amount);
}
else
{
UtilPlayer.message(caller, F.main("Item", "Player " + F.name(playerName) + " does not exist!"));
}
else
{
UtilPlayer.message(caller, F.main("Item", "Player " + F.name(playerName) + " does not exist!"));
}
}
});
}
}

View File

@ -27,8 +27,8 @@ public class InventoryRepository extends RepositoryBase
private static String INSERT_CATEGORY = "INSERT INTO itemCategories (name) VALUES (?);";
private static String RETRIEVE_CATEGORIES = "SELECT id, name FROM itemCategories;";
private static String INSERT_CLIENT_INVENTORY = "INSERT INTO accountInventory (accountId, itemId, count) SELECT accounts.id, ?, ? FROM accounts WHERE accounts.uuid = ? ON DUPLICATE KEY UPDATE count=count + VALUES(count);";
private static String UPDATE_CLIENT_INVENTORY = "UPDATE accountInventory AS AI INNER JOIN accounts ON AI.accountId = accounts.id SET AI.count = AI.count + ? WHERE accounts.uuid = ? AND AI.itemId = ?;";
private static String INSERT_CLIENT_INVENTORY = "INSERT INTO accountInventory (accountId, itemId, count) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE count=count + VALUES(count);";
private static String UPDATE_CLIENT_INVENTORY = "UPDATE accountInventory SET count = count + ? WHERE accountId = ? AND itemId = ?;";
public InventoryRepository(JavaPlugin plugin)
{
@ -96,10 +96,14 @@ public class InventoryRepository extends RepositoryBase
return items;
}
public boolean incrementClientInventoryItem(String uuid, int itemId, int count)
public boolean incrementClientInventoryItem(int accountId, int itemId, int count)
{
if (executeUpdate(UPDATE_CLIENT_INVENTORY, new ColumnInt("count", count), new ColumnVarChar("uuid", 100, uuid), new ColumnInt("itemid", itemId)) < 1)
return executeUpdate(INSERT_CLIENT_INVENTORY, new ColumnInt("itemid", itemId), new ColumnInt("count", count), new ColumnVarChar("uuid", 100, uuid)) > 0;
System.out.println("Updating " + accountId + "'s " + itemId + " with " + count);
if (executeUpdate(UPDATE_CLIENT_INVENTORY, new ColumnInt("count", count), new ColumnInt("id", accountId), new ColumnInt("itemid", itemId)) < 1)
{
System.out.println("Inserting " + accountId + "'s " + itemId + " with " + count);
return executeUpdate(INSERT_CLIENT_INVENTORY, new ColumnInt("id", accountId), new ColumnInt("itemid", itemId), new ColumnInt("count", count)) > 0;
}
else
return true;
}

View File

@ -112,7 +112,7 @@ public class PreferencesManager extends MiniDbClientPlugin<UserPreferences>
}
@Override
public String getQuery(String uuid, String name)
public String getQuery(int accountId, String uuid, String name)
{
return "SELECT games, visibility, showChat, friendChat, privateMessaging, partyRequests, invisibility, forcefield, showMacReports, ignoreVelocity, pendingFriendRequests, friendDisplayInventoryUI FROM accountPreferences WHERE accountPreferences.uuid = '" + uuid + "' LIMIT 1;";
}

View File

@ -76,9 +76,9 @@ public class ReportManager {
reportRepository.removeElement(String.valueOf(reportId)); // Remove report from redis database
removeActiveReport(reportId);
int closerId = getPlayerAccount(reportCloser).GetAccountId();
int closerId = getPlayerAccount(reportCloser).getAccountId();
String playerName = getReport(reportId).getPlayerName();
int playerId = getPlayerAccount(playerName).GetAccountId();
int playerId = getPlayerAccount(playerName).getAccountId();
String server = null; // TODO: Get current server name
reportSqlRepository.logReport(reportId, playerId, server, closerId, result, reason);
@ -86,7 +86,7 @@ public class ReportManager {
for (String reporterName : report.getReporters())
{
CoreClient reporterAccount = getPlayerAccount(reporterName);
ReportProfile reportProfile = getReportProfile(String.valueOf(reporterAccount.GetAccountId()));
ReportProfile reportProfile = getReportProfile(String.valueOf(reporterAccount.getAccountId()));
reportProfile.onReportClose(result);
reportProfiles.addElement(reportProfile);
}
@ -113,14 +113,14 @@ public class ReportManager {
// TODO: Send display message to handler when they arrive on the server
// with info about the case/report.
int handlerId = getPlayerAccount(reportHandler).GetAccountId();
int handlerId = getPlayerAccount(reportHandler).getAccountId();
reportSqlRepository.logReportHandling(reportId, handlerId); // Log handling into sql database
}
}
public void reportPlayer(Player reporter, Player reportedPlayer, String reason)
{
int reporterId = getPlayerAccount(reporter).GetAccountId();
int reporterId = getPlayerAccount(reporter).getAccountId();
ReportProfile reportProfile = getReportProfile(String.valueOf(reporterId));
if (reportProfile.canReport())
@ -232,7 +232,7 @@ public class ReportManager {
private int getAccountId(String playerName)
{
return getPlayerAccount(playerName).GetAccountId();
return getPlayerAccount(playerName).getAccountId();
}
/**

View File

@ -53,7 +53,7 @@ public class CoinReward extends Reward
{
}
}, "Treasure Chest", player.getName(), player.getUniqueId(), gemsToReward);
}, "Treasure Chest", player.getName(), _donationManager.getClientManager().Get(player).getAccountId(), gemsToReward);
return new RewardData(getRarity().getColor() + gemsToReward + " Coins", new ItemStack(175));
}

View File

@ -31,7 +31,7 @@ public class UnknownPackageReward extends Reward
@Override
protected RewardData giveRewardCustom(Player player)
{
_donationManager.PurchaseUnknownSalesPackage(null, player.getName(), player.getUniqueId(), _packageName, true, 0, true);
_donationManager.PurchaseUnknownSalesPackage(null, player.getName(), _donationManager.getClientManager().Get(player).getAccountId(), _packageName, true, 0, true);
return new RewardData(getRarity().getColor() + _name, _itemStack);
}

View File

@ -147,7 +147,7 @@ public class ConfirmationPage<PluginType extends MiniPlugin, ShopType extends Sh
{
showResultsPage(response);
}
}, getPlayer().getName(), getPlayer().getUniqueId(), _salesItem.GetName(), getCurrencyType() == CurrencyType.Coins, _salesItem.GetCost(getCurrencyType()), _salesItem.OneTimePurchase());
}, getPlayer().getName(), getClientManager().Get(getPlayer()).getAccountId(), _salesItem.GetName(), getCurrencyType() == CurrencyType.Coins, _salesItem.GetCost(getCurrencyType()), _salesItem.OneTimePurchase());
}
_taskId = getPlugin().getScheduler().scheduleSyncRepeatingTask(getPlugin().getPlugin(), this, 2L, 2L);

View File

@ -9,6 +9,7 @@ import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniDbClientPlugin;
import mineplex.core.account.CoreClient;
import mineplex.core.account.CoreClientManager;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.common.util.UtilServer;
@ -92,26 +93,22 @@ public class StatsManager extends MiniDbClientPlugin<PlayerStats>
}
else
{
synchronized (_statSync)
{
addToQueue(statName, player, value);
}
addToQueue(statName, player, value);
}
}
private void addToQueue(String statName, Player player, int value)
{
if (!_statUploadQueue.containsKey(player))
synchronized (_statSync)
{
_statUploadQueue.put(player, new NautHashMap<String, Integer>());
if (!_statUploadQueue.containsKey(player))
_statUploadQueue.put(player, new NautHashMap<String, Integer>());
if (!_statUploadQueue.get(player).containsKey(statName))
_statUploadQueue.get(player).put(statName, 0);
_statUploadQueue.get(player).put(statName, _statUploadQueue.get(player).get(statName) + value);
}
if (!_statUploadQueue.get(player).containsKey(statName))
{
_statUploadQueue.get(player).put(statName, 0);
}
_statUploadQueue.get(player).put(statName, _statUploadQueue.get(player).get(statName) + value);
}
protected void saveStats()
@ -121,7 +118,7 @@ public class StatsManager extends MiniDbClientPlugin<PlayerStats>
try
{
NautHashMap<String, NautHashMap<Integer, Integer>> uploadQueue = new NautHashMap<String, NautHashMap<Integer, Integer>>();
NautHashMap<Integer, NautHashMap<Integer, Integer>> uploadQueue = new NautHashMap<Integer, NautHashMap<Integer, Integer>>();
synchronized (_statSync)
{
@ -132,7 +129,7 @@ public class StatsManager extends MiniDbClientPlugin<PlayerStats>
if (player.isOnline())
continue;
String uploadKey = player.getUniqueId().toString();
int uploadKey = ClientManager.getCachedClientAccountId(player.getUniqueId());
uploadQueue.put(uploadKey, new NautHashMap<Integer, Integer>());
@ -155,14 +152,14 @@ public class StatsManager extends MiniDbClientPlugin<PlayerStats>
}
}
public boolean incrementStat(final String uuidString, final String statName, final int value)
public boolean incrementStat(final int accountId, final String statName, final int value)
{
if (_stats.containsKey(statName))
return false;
final NautHashMap<String, NautHashMap<Integer, Integer>> uploadQueue = new NautHashMap<String, NautHashMap<Integer, Integer>>();
uploadQueue.put(uuidString, new NautHashMap<Integer, Integer>());
uploadQueue.get(uuidString).put(_stats.get(statName), value);
final NautHashMap<Integer, NautHashMap<Integer, Integer>> uploadQueue = new NautHashMap<Integer, NautHashMap<Integer, Integer>>();
uploadQueue.put(accountId, new NautHashMap<Integer, Integer>());
uploadQueue.get(accountId).put(_stats.get(statName), value);
runAsync(new Runnable()
{
@ -200,8 +197,8 @@ public class StatsManager extends MiniDbClientPlugin<PlayerStats>
}
@Override
public String getQuery(String uuid, String name)
public String getQuery(int accountId, String uuid, String name)
{
return "SELECT stats.name, value FROM accountStats INNER JOIN stats ON stats.id = accountStats.statId INNER JOIN accounts ON accountStats.accountId = accounts.id WHERE accounts.uuid = '" + uuid + "';";
return "SELECT stats.name, value FROM accountStats INNER JOIN stats ON stats.id = accountStats.statId WHERE accountStats.accountId = '" + accountId + "';";
}
}

View File

@ -77,7 +77,7 @@ public class StatsRepository extends RepositoryBase
}
@SuppressWarnings("rawtypes")
public void saveStats(NautHashMap<String, NautHashMap<Integer, Integer>> uploadQueue)
public void saveStats(NautHashMap<Integer, NautHashMap<Integer, Integer>> uploadQueue)
{
try
{
@ -86,23 +86,23 @@ public class StatsRepository extends RepositoryBase
List<Update> updates = new ArrayList<>();
List<Insert> inserts = new ArrayList<>();
for (String uuid : uploadQueue.keySet())
for (int accountId : uploadQueue.keySet())
{
for (Integer statId : uploadQueue.get(uuid).keySet())
for (Integer statId : uploadQueue.get(accountId).keySet())
{
Update update = context
.update(Tables.accountStats)
.set(Tables.accountStats.value, Tables.accountStats.value.plus(uploadQueue.get(uuid).get(statId)))
.where(Tables.accountStats.accountId.eq(context.select(Tables.accounts.id).from(Tables.accounts).where(Tables.accounts.uuid.eq(uuid))))
.set(Tables.accountStats.value, Tables.accountStats.value.plus(uploadQueue.get(accountId).get(statId)))
.where(Tables.accountStats.accountId.eq(accountId))
.and(Tables.accountStats.statId.eq(statId));
updates.add(update);
Insert insert = context
.insertInto(Tables.accountStats)
.set(Tables.accountStats.accountId, context.select(Tables.accounts.id).from(Tables.accounts).where(Tables.accounts.uuid.eq(uuid)))
.set(Tables.accountStats.accountId, accountId)
.set(Tables.accountStats.statId, statId)
.set(Tables.accountStats.value, uploadQueue.get(uuid).get(statId));
.set(Tables.accountStats.value, uploadQueue.get(accountId).get(statId));
inserts.add(insert);
}

View File

@ -1,13 +1,11 @@
package mineplex.core.stats.command;
import java.util.UUID;
import org.bukkit.entity.Player;
import mineplex.core.account.CoreClient;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UUIDFetcher;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.stats.StatsManager;
@ -31,20 +29,29 @@ public class GiveStatCommand extends CommandBase<StatsManager>
{
Player player = UtilPlayer.searchOnline(caller, args[0], true);
String statName = args[1];
String tempStatName = args[1];
for (int i = 2; i < args.length - 1; i++)
{
statName += " " + args[i];
tempStatName += " " + args[i];
}
final String statName = tempStatName;
if (player == null)
{
UUID uuid = UUIDFetcher.getUUIDOf(args[0]);
if (uuid != null)
Plugin.getClientManager().loadClientByName(args[0], new Runnable()
{
Plugin.incrementStat(uuid.toString(), statName, Integer.parseInt(args[args.length - 1]));
}
public void run()
{
final CoreClient client = Plugin.getClientManager().Get(args[0]);
if (client != null)
Plugin.incrementStat(client.getAccountId(), statName, Integer.parseInt(args[args.length - 1]));
else
caller.sendMessage(F.main(Plugin.getName(), "Couldn't find " + args[0] + "'s account!"));
}
});
}
else
{

View File

@ -258,7 +258,7 @@ public class NewsManager extends MiniPlugin
double healthPercent = (double)_newsIndex/(double)(_news.length-1);
String text = _news[_newsIndex];
UtilTextTop.display(text, true, UtilServer.getPlayers());
UtilTextTop.display(text, UtilServer.getPlayers());
for (Creature pet : Manager.getPetManager().getPets())
{
if (pet instanceof Wither)

View File

@ -216,8 +216,8 @@ public class PollManager extends MiniDbClientPlugin<PlayerPollData>
}
@Override
public String getQuery(String uuid, String name)
public String getQuery(int accountId, String uuid, String name)
{
return "SELECT pollId, value FROM accountPolls INNER JOIN accounts ON accountPolls.accountId = accounts.id WHERE accounts.uuid = '" + uuid + "';";
return "SELECT pollId, value FROM accountPolls WHERE accountPolls.accountId = '" + accountId + "';";
}
}

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jre7"/>
<classpathentry combineaccessrules="false" kind="src" path="/Mineplex.ServerData"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Mineplex.PlayerCache</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.7

View File

@ -0,0 +1,37 @@
package mineplex.playerCache;
import java.util.UUID;
import mineplex.serverdata.Region;
import mineplex.serverdata.redis.RedisDataRepository;
import mineplex.serverdata.servers.ServerManager;
public class PlayerCache
{
private RedisDataRepository<PlayerInfo> _repository;
public PlayerCache()
{
_repository = new RedisDataRepository<PlayerInfo>(
ServerManager.getMasterConnection(),
ServerManager.getSlaveConnection(),
Region.ALL,
PlayerInfo.class,
"playercache");
}
public void addPlayer(PlayerInfo player)
{
_repository.addElement(player, 60 * 60 * 6); // 6 Hours
}
public PlayerInfo getPlayer(UUID uuid)
{
return _repository.getElement(uuid.toString());
}
public void clean()
{
_repository.clean();
}
}

View File

@ -0,0 +1,86 @@
package mineplex.playerCache;
import java.util.UUID;
import mineplex.serverdata.data.Data;
public class PlayerInfo implements Data
{
private int _id;
private UUID _uuid;
private String _name;
private boolean _online;
private long _lastUniqueLogin;
private long _loginTime;
private int _sessionId;
private int _version;
public PlayerInfo(int id, UUID uuid, String name, int version)
{
_id = id;
_uuid = uuid;
_name = name;
_version = version;
}
@Override
public String getDataId()
{
return _uuid.toString();
}
public int getId()
{
return _id;
}
public UUID getUUID()
{
return _uuid;
}
public String getName()
{
return _name;
}
public boolean getOnline()
{
return _online;
}
public long getLastUniqueLogin()
{
return _lastUniqueLogin;
}
public long getLoginTime()
{
return _loginTime;
}
public int getSessionId()
{
return _sessionId;
}
public int getVersion()
{
return _version;
}
public void setSessionId(int sessionId)
{
_sessionId = sessionId;
}
public void setName(String name)
{
_name = name;
}
public void setVersion(int version)
{
_version = version;
}
}

View File

@ -0,0 +1,102 @@
package mineplex.servermonitor;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import com.google.gson.Gson;
public class MinecraftPing {
/**
* Fetches a {@link MinecraftPingReply} for the supplied hostname.
* <b>Assumed timeout of 2s and port of 25565.</b>
*
* @param hostname - a valid String hostname
* @return {@link MinecraftPingReply}
* @throws IOException
*/
public MinecraftPingReply getPing(final String hostname) throws IOException {
return this.getPing(new MinecraftPingOptions().setHostname(hostname));
}
/**
* Fetches a {@link MinecraftPingReply} for the supplied options.
*
* @param options - a filled instance of {@link MinecraftPingOptions}
* @return {@link MinecraftPingReply}
* @throws IOException
*/
public MinecraftPingReply getPing(final MinecraftPingOptions options) throws IOException {
MinecraftPingUtil.validate(options.getHostname(), "Hostname cannot be null.");
MinecraftPingUtil.validate(options.getPort(), "Port cannot be null.");
final Socket socket = new Socket();
socket.connect(new InetSocketAddress(options.getHostname(), options.getPort()), options.getTimeout());
final DataInputStream in = new DataInputStream(socket.getInputStream());
final DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//> Handshake
ByteArrayOutputStream handshake_bytes = new ByteArrayOutputStream();
DataOutputStream handshake = new DataOutputStream(handshake_bytes);
handshake.writeByte(MinecraftPingUtil.PACKET_HANDSHAKE);
MinecraftPingUtil.writeVarInt(handshake, MinecraftPingUtil.PROTOCOL_VERSION);
MinecraftPingUtil.writeVarInt(handshake, options.getHostname().length());
handshake.writeBytes(options.getHostname());
handshake.writeShort(options.getPort());
MinecraftPingUtil.writeVarInt(handshake, MinecraftPingUtil.STATUS_HANDSHAKE);
MinecraftPingUtil.writeVarInt(out, handshake_bytes.size());
out.write(handshake_bytes.toByteArray());
//> Status request
out.writeByte(0x01); // Size of packet
out.writeByte(MinecraftPingUtil.PACKET_STATUSREQUEST);
//< Status response
MinecraftPingUtil.readVarInt(in); // Size
int id = MinecraftPingUtil.readVarInt(in);
MinecraftPingUtil.io(id == -1, "Server prematurely ended stream.");
MinecraftPingUtil.io(id != MinecraftPingUtil.PACKET_STATUSREQUEST, "Server returned invalid packet.");
int length = MinecraftPingUtil.readVarInt(in);
MinecraftPingUtil.io(length == -1, "Server prematurely ended stream.");
MinecraftPingUtil.io(length == 0, "Server returned unexpected value.");
byte[] data = new byte[length];
in.readFully(data);
String json = new String(data, options.getCharset());
//> Ping
out.writeByte(0x09); // Size of packet
out.writeByte(MinecraftPingUtil.PACKET_PING);
out.writeLong(System.currentTimeMillis());
//< Ping
MinecraftPingUtil.readVarInt(in); // Size
id = MinecraftPingUtil.readVarInt(in);
MinecraftPingUtil.io(id == -1, "Server prematurely ended stream.");
//MinecraftPingUtil.io(id != MinecraftPingUtil.PACKET_PING, "Server returned invalid packet.");
// Close
handshake.close();
handshake_bytes.close();
out.close();
in.close();
socket.close();
return new Gson().fromJson(json, MinecraftPingReply.class);
}
}

View File

@ -0,0 +1,45 @@
package mineplex.servermonitor;
public class MinecraftPingOptions
{
private String hostname;
private int port = 25565;
private int timeout = 2000;
private String charset = "UTF-8";
public MinecraftPingOptions setHostname(String hostname) {
this.hostname = hostname;
return this;
}
public MinecraftPingOptions setPort(int port) {
this.port = port;
return this;
}
public MinecraftPingOptions setTimeout(int timeout) {
this.timeout = timeout;
return this;
}
public MinecraftPingOptions setCharset(String charset) {
this.charset = charset;
return this;
}
public String getHostname() {
return this.hostname;
}
public int getPort() {
return this.port;
}
public int getTimeout() {
return this.timeout;
}
public String getCharset() {
return this.charset;
}
}

View File

@ -0,0 +1,103 @@
package mineplex.servermonitor;
import java.util.List;
public class MinecraftPingReply {
private String description;
private Players players;
private Version version;
private String favicon;
/**
* @return the MOTD
*/
public String getDescription() {
return this.description;
}
public Players getPlayers() {
return this.players;
}
/**
* @return @{link Version}
*/
public Version getVersion() {
return this.version;
}
/**
* @return Base64 encoded favicon image
*/
public String getFavicon() {
return this.favicon;
}
public class Players {
private int max;
private int online;
private List<Player> sample;
/**
* @return Maximum player count
*/
public int getMax() {
return this.max;
}
/**
* @return Online player count
*/
public int getOnline() {
return this.online;
}
/**
* @return List of some players (if any) specified by server
*/
public List<Player> getSample() {
return this.sample;
}
}
public class Player {
private String name;
private String id;
/**
* @return Name of player
*/
public String getName() {
return this.name;
}
/**
* @return Unknown
*/
public String getId() {
return this.id;
}
}
public class Version {
private String name;
private int protocol;
/**
* @return Version name (ex: 13w41a)
*/
public String getName() {
return this.name;
}
/**
* @return Protocol version
*/
public int getProtocol() {
return this.protocol;
}
}
}

View File

@ -0,0 +1,63 @@
package mineplex.servermonitor;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class MinecraftPingUtil {
public static byte PACKET_HANDSHAKE = 0x00, PACKET_STATUSREQUEST = 0x00, PACKET_PING = 0x01;
public static int PROTOCOL_VERSION = 4;
public static int STATUS_HANDSHAKE = 1;
public static void validate(final Object o, final String m)
{
if (o == null)
{
throw new RuntimeException(m);
}
}
public static void io(final boolean b, final String m) throws IOException
{
if (b)
{
throw new IOException(m);
}
}
public static int readVarInt(DataInputStream in) throws IOException
{
int i = 0;
int j = 0;
while (true) {
int k = in.readByte();
i |= (k & 0x7F) << j++ * 7;
if (j > 5)
throw new RuntimeException("VarInt too big");
if ((k & 0x80) != 128)
break;
}
return i;
}
public static void writeVarInt(DataOutputStream out, int paramInt) throws IOException
{
while (true)
{
if ((paramInt & 0xFFFFFF80) == 0)
{
out.writeByte(paramInt);
return;
}
out.writeByte(paramInt & 0x7F | 0x80);
paramInt >>>= 7;
}
}
}

View File

@ -152,8 +152,8 @@ public class StatusHistoryRepository
for (DedicatedServer dedicatedServer : dedicatedServers)
{
double usedCpu = (1d - (double)dedicatedServer.getAvailableCpu() / (double)dedicatedServer.getMaxCpu()) * 100d;
double usedRam = (1d - (double)dedicatedServer.getAvailableRam() / (double)dedicatedServer.getMaxRam()) * 100d;
double usedCpu = dedicatedServer.getMaxCpu() == 0 ? 0 : (1d - (double)dedicatedServer.getAvailableCpu() / (double)dedicatedServer.getMaxCpu()) * 100d;
double usedRam = dedicatedServer.getMaxRam() == 0 ? 0 : (1d - (double)dedicatedServer.getAvailableRam() / (double)dedicatedServer.getMaxRam()) * 100d;
preparedStatement.setString(1, dedicatedServer.getName());
preparedStatement.setString(2, dedicatedServer.getPrivateAddress());

View File

@ -4,6 +4,7 @@ import java.util.UUID;
import org.bukkit.entity.Player;
import mineplex.core.account.CoreClient;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.F;
@ -18,20 +19,28 @@ public class CoinCommand extends CommandBase<SalesPackageManager>
}
@Override
public void Execute(Player caller, String[] args)
public void Execute(final Player caller, String[] args)
{
if (args == null || args.length != 2)
return;
String playerName = args[0];
int amount = Integer.parseInt(args[1]);
final String playerName = args[0];
final int amount = Integer.parseInt(args[1]);
UUID uuid = Plugin.getClientManager().loadUUIDFromDB(playerName);
if (uuid == null)
UUIDFetcher.getUUIDOf(playerName);
Plugin.getDonationManager().RewardCoins(null, caller.getName(), playerName, uuid, amount);
caller.sendMessage(F.main(Plugin.getName(), "Added " + amount + " coins to " + playerName + "'s account!"));
Plugin.getClientManager().loadClientByName(playerName, new Runnable()
{
public void run()
{
CoreClient client = Plugin.getClientManager().Get(playerName);
if (client != null)
{
Plugin.getDonationManager().RewardCoins(null, caller.getName(), playerName, client.getAccountId(), amount);
caller.sendMessage(F.main(Plugin.getName(), "Added " + amount + " coins to " + playerName + "'s account!"));
}
else
caller.sendMessage(F.main(Plugin.getName(), "Couldn't find " + playerName + "'s account!"));
}
});
}
}

View File

@ -4,6 +4,7 @@ import java.util.UUID;
import org.bukkit.entity.Player;
import mineplex.core.account.CoreClient;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.F;
@ -18,26 +19,37 @@ public class GemHunterCommand extends CommandBase<SalesPackageManager>
}
@Override
public void Execute(Player caller, String[] args)
public void Execute(final Player caller, String[] args)
{
if (args == null || args.length != 2)
return;
String playerName = args[0];
int amount = Integer.parseInt(args[1]);
int experience = 0;
UUID uuid = Plugin.getClientManager().loadUUIDFromDB(playerName);
final String playerName = args[0];
final int amount = Integer.parseInt(args[1]);
int tempExp = 0;
if (uuid == null)
UUIDFetcher.getUUIDOf(playerName);
if (amount == 4)
experience = 70000;
tempExp = 70000;
else if (amount == 8)
experience = 220000;
tempExp = 220000;
Plugin.getDonationManager().PurchaseUnknownSalesPackage(null, playerName, uuid, "Gem Hunter Level " + amount, false, 0, false);
Plugin.getStatsManager().incrementStat(uuid.toString(), "Global.GemsEarned", experience);
caller.sendMessage(F.main(Plugin.getName(), "Added Level " + amount + " Gem Hunter to " + playerName + "'s account!"));
final int experience = tempExp;
Plugin.getClientManager().loadClientByName(playerName, new Runnable()
{
public void run()
{
CoreClient client = Plugin.getClientManager().Get(playerName);
if (client != null)
{
Plugin.getDonationManager().PurchaseUnknownSalesPackage(null, playerName, client.getAccountId(), "Gem Hunter Level " + amount, false, 0, false);
Plugin.getStatsManager().incrementStat(client.getAccountId(), "Global.GemsEarned", experience);
caller.sendMessage(F.main(Plugin.getName(), "Added Level " + amount + " Gem Hunter to " + playerName + "'s account!"));
}
else
caller.sendMessage(F.main(Plugin.getName(), "Couldn't find " + playerName + "'s account!"));
}
});
}
}

View File

@ -4,6 +4,7 @@ import java.util.UUID;
import org.bukkit.entity.Player;
import mineplex.core.account.CoreClient;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.Callback;
@ -37,12 +38,6 @@ public class ItemCommand extends CommandBase<SalesPackageManager>
}
final String itemName = tempName;
UUID uuidLookup = Plugin.getClientManager().loadUUIDFromDB(playerName);
if (uuidLookup == null)
uuidLookup = UUIDFetcher.getUUIDOf(playerName);
final UUID uuid = uuidLookup;
final int amount = amountSpecified;
if (!Plugin.getInventoryManager().validCategory(category))
@ -57,23 +52,37 @@ public class ItemCommand extends CommandBase<SalesPackageManager>
return;
}
Plugin.getDonationManager().PurchaseUnknownSalesPackage(new Callback<TransactionResponse>()
Plugin.getClientManager().loadClientByName(playerName, new Runnable()
{
public void run(TransactionResponse data)
public void run()
{
Plugin.getInventoryManager().addItemToInventoryForOffline(new Callback<Boolean>()
final UUID uuid = Plugin.getClientManager().loadUUIDFromDB(playerName);
final CoreClient client = Plugin.getClientManager().Get(playerName);
if (uuid != null)
{
public void run(Boolean success)
Plugin.getDonationManager().PurchaseUnknownSalesPackage(new Callback<TransactionResponse>()
{
if (success)
UtilPlayer.message(caller, F.main(Plugin.getName(), playerName + " received " + amount + " " + itemName + "."));
else
public void run(TransactionResponse data)
{
UtilPlayer.message(caller, F.main(Plugin.getName(), "ERROR processing " + playerName + " " + amount + " " + itemName + "."));
Plugin.getInventoryManager().addItemToInventoryForOffline(new Callback<Boolean>()
{
public void run(Boolean success)
{
if (success)
UtilPlayer.message(caller, F.main(Plugin.getName(), playerName + " received " + amount + " " + itemName + "."));
else
{
UtilPlayer.message(caller, F.main(Plugin.getName(), "ERROR processing " + playerName + " " + amount + " " + itemName + "."));
}
}
}, uuid, category, itemName, amount);
}
}
}, uuid.toString(), category, itemName, amount);
}, playerName, client.getAccountId(), (amount == 1 ? itemName : itemName + " " + amount), false, 0, false);
}
else
caller.sendMessage(F.main(Plugin.getName(), "Couldn't find " + playerName + "'s account!"));
}
}, playerName, uuid, (amount == 1 ? itemName : itemName + " " + amount), false, 0, false);
});
}
}

View File

@ -399,7 +399,7 @@ public class Halloween extends SoloGame
{
for (Player player : GetPlayers(false))
{
Manager.GetDonation().PurchaseUnknownSalesPackage(null, player.getName(), player.getUniqueId(), "Pumpling", false, 0, true);
Manager.GetDonation().PurchaseUnknownSalesPackage(null, player.getName(), Manager.GetClients().Get(player).getAccountId(), "Pumpling", false, 0, true);
Manager.GetGame().AddGems(player, 30, "Killing the Pumpkin King", false, false);
Manager.GetGame().AddGems(player, 10, "Participation", false, false);
}

View File

@ -217,7 +217,7 @@ public class HalloweenManager implements Listener
event.setCancelled(true);
event.getItem().remove();
Manager.GetDonation().RewardCoins(null, "Halloween Pumpkin", event.getPlayer().getName(), event.getPlayer().getUniqueId(), 4 * event.getItem().getItemStack().getAmount());
Manager.GetDonation().RewardCoins(null, "Halloween Pumpkin", event.getPlayer().getName(), Manager.GetClients().Get(event.getPlayer()).getAccountId(), 4 * event.getItem().getItemStack().getAmount());
event.getPlayer().getWorld().playSound(event.getPlayer().getLocation(), Sound.ORB_PICKUP, 1f, 2f);
}