Merge branch 'master' of ssh://184.154.0.242:7999/min/mineplex

Conflicts:
	Plugins/Mineplex.Core.Common/src/mineplex/core/common/Rank.java
This commit is contained in:
Chiss 2014-07-18 08:32:35 +10:00
commit b719916bb8
238 changed files with 10035 additions and 4635 deletions

View File

@ -3,6 +3,8 @@
<component name="ProjectCodeStyleSettingsManager">
<option name="PER_PROJECT_SETTINGS">
<value>
<option name="FIELD_NAME_PREFIX" value="_" />
<option name="STATIC_FIELD_NAME_PREFIX" value="_" />
<option name="USE_SINGLE_CLASS_IMPORTS" value="false" />
<XML>
<option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
@ -15,13 +17,6 @@
<option name="WHILE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="SPACE_BEFORE_IF_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_WHILE_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_FOR_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_TRY_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_CATCH_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_SWITCH_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_SYNCHRONIZED_PARENTHESES" value="false" />
<option name="ENUM_CONSTANTS_WRAP" value="2" />
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />

View File

@ -0,0 +1,125 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="" />
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

View File

@ -126,6 +126,30 @@
</jar>
<copy file="../bin/Mineplexer.jar" todir="../../Testing/Proxy/plugins"/>
</target>
<target name ="DDoSProtectionSwitcher" description="DDoSProtectionSwitcher">
<jar jarfile="../bin/DDoSProtectionSwitcher.jar">
<fileset dir="../Mineplex.DDoSProtectionSwitcher/bin">
<include name="**/*.class"/>
</fileset>
<zipfileset src="../Libraries/mysql.zip" />
<manifest>
<attribute name="Main-Class"
value="mineplex.ddos.DDoSProtectionSwitcher"/>
</manifest>
<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/gson-2.2.1.jar" />
<zipfileset src="../Libraries/javax.mail.jar" />
<zipfileset src="../Libraries/commons-logging-1.1.1.jar" />
<zipfileset src="../Libraries/commons-codec-1.6.jar" />
</jar>
<copy file="../bin/DDoSProtectionSwitcher.jar" todir="../../Testing/DDoSProtectionSwitcher/"/>
</target>
<target name ="ServerMonitor" description="ServerMonitor">
<jar jarfile="../bin/ServerMonitor.jar">
<fileset dir="../Mineplex.Core.Common/bin">

View File

@ -8,6 +8,5 @@
<classpathentry combineaccessrules="false" kind="src" path="/Mineplex.Minecraft.Game.Core"/>
<classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/bukkit.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/Mineplex.Core"/>
<classpathentry combineaccessrules="false" kind="src" path="/Nautilus.Core"/>
<classpathentry kind="output" path="bin"/>
</classpath>

Binary file not shown.

View File

@ -1,103 +1,22 @@
package mineplex.bungee;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mineplex.bungee.lobbyBalancer.LobbyBalancer;
import mineplex.bungee.motd.MotdManager;
import mineplex.bungee.playerCount.PlayerCount;
import mineplex.bungee.playerStats.PlayerStats;
import mineplex.bungee.status.InternetStatus;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.conf.YamlConfig;
public class Mineplexer extends Plugin
{
@Override
public void onEnable()
{
//_dynamicServers = new GlobalServer(this);
/*
try
{
Field config = YamlConfig.class.getDeclaredField("config");
config.setAccessible(true);
Map configMap = (Map)config.get(getProxy().getConfigurationAdapter());
System.out.println("Printing groups.");
for (String playerName : ((HashMap<String, List<String>>)configMap.get("groups")).keySet())
{
System.out.println(playerName);
for (String rank : ((HashMap<String, List<String>>)configMap.get("groups")).get(playerName))
{
System.out.println("-" + rank);
}
}
((HashMap<String, List<String>>)configMap.get("groups")).clear();
((HashMap<String, List<String>>)configMap.get("groups")).put("defek7", Arrays.asList("admin", "owner"));
config.set(getProxy().getConfigurationAdapter(), configMap);
System.out.println("Printing groups.");
for (String playerName : ((HashMap<String, List<String>>)configMap.get("groups")).keySet())
{
System.out.println(playerName);
for (String rank : ((HashMap<String, List<String>>)configMap.get("groups")).get(playerName))
{
System.out.println("-" + rank);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
*/
{
new MotdManager(this);
new LobbyBalancer(this);
new PlayerCount(this);
new FileUpdater(this);
new PlayerStats(this);
new InternetStatus(this);
}
protected String readString(DataInputStream dataInputStream, int maxLength) throws IOException
{
short length = dataInputStream.readShort();
if (length > maxLength)
{
throw new IOException("Received string length longer than maximum allowed (" + length + " > " + maxLength + ")");
}
else if (length < 0)
{
throw new IOException("Received string length is less than zero! Weird string!");
}
else
{
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < length; i++)
{
stringBuilder.append(dataInputStream.readChar());
}
return stringBuilder.toString();
}
}
protected void writeString(String string, DataOutputStream dataOutputStream) throws IOException
{
dataOutputStream.writeShort(string.length());
dataOutputStream.writeChars(string);
}
}

View File

@ -1,29 +0,0 @@
package mineplex.bungee.groupManager;
import java.util.concurrent.TimeUnit;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
public class GroupManager implements Listener, Runnable
{
private Plugin _plugin;
private GroupRepository _repository;
public GroupManager(Plugin plugin)
{
_plugin = plugin;
_plugin.getProxy().getScheduler().schedule(_plugin, this, 3L, 3L, TimeUnit.SECONDS);
_plugin.getProxy().getPluginManager().registerListener(_plugin, this);
_repository = new GroupRepository();
_repository.initialize();
}
@Override
public void run()
{
}
}

View File

@ -1,194 +0,0 @@
package mineplex.bungee.groupManager;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class GroupRepository
{
private Connection _connection = null;
private String _connectionString = "jdbc:mysql://db.mineplex.com:3306/BungeeServers?autoReconnect=true&failOverReadOnly=false&maxReconnects=10";
private String _userName = "root";
private String _password = "tAbechAk3wR7tuTh";
private static String CREATE_GROUPS_TABLE = "CREATE TABLE IF NOT EXISTS groups (id INT NOT NULL AUTO_INCREMENT, name VARCHAR(256), updated LONG, players INT, maxPlayers INT, ram INT, maxRam INT, PRIMARY KEY (id));";
private static String INSERT_PLAYER_COUNT = "INSERT INTO BungeeServers(address, updated, players, maxPlayers, ram, maxRam) values(?, now(), ?, ?, ?, ?);";
private static String UPDATE_PLAYER_COUNT = "UPDATE BungeeServers SET updated = now(), players = ?, maxPlayers = ?, ram = ?, maxRam = ? WHERE id = ?;";
private static String RETRIEVE_ID = "SELECT id FROM BungeeServers WHERE address = ?;";
private static String RETRIEVE_PLAYER_COUNT = "SELECT SUM(players) AS playerCount, SUM(maxPlayers) AS maxPlayerCount FROM BungeeServers WHERE TIME_TO_SEC(TIMEDIFF(now(), BungeeServers.updated)) < 10;";
private int _id = -1;
private String _address;
private int _maxPlayers = 0;
public void initialize()
{
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
PreparedStatement preparedStatementRetrieve = null;
PreparedStatement preparedStatementInsert = null;
try
{
if (_connection == null || _connection.isClosed())
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
// Create table
preparedStatement = _connection.prepareStatement(CREATE_GROUPS_TABLE);
preparedStatement.execute();
// Retrieve id
preparedStatementRetrieve = _connection.prepareStatement(RETRIEVE_ID);
preparedStatementRetrieve.setString(1, _address);
resultSet = preparedStatementRetrieve.executeQuery();
while (resultSet.next())
{
_id = resultSet.getInt("id");
}
// Insert if not there
if (_id == -1)
{
preparedStatementInsert = _connection.prepareStatement(INSERT_PLAYER_COUNT, Statement.RETURN_GENERATED_KEYS);
preparedStatementInsert.setString(1, _address);
preparedStatementInsert.setInt(2, 0);
preparedStatementInsert.setInt(3, _maxPlayers);
preparedStatementInsert.setInt(4, (int) ((Runtime.getRuntime().maxMemory() - Runtime.getRuntime().freeMemory()) / 1048576));
preparedStatementInsert.setInt(5, (int) (Runtime.getRuntime().maxMemory() / 1048576));
int affectedRows = preparedStatementInsert.executeUpdate();
if (affectedRows == 0)
{
throw new SQLException("Creating bungee server failed, no rows affected.");
}
resultSet.close();
resultSet = preparedStatementInsert.getGeneratedKeys();
if (resultSet.next())
{
_id = resultSet.getInt(1);
System.out.println("id = " + _id);
}
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (preparedStatementRetrieve != null)
{
try
{
preparedStatementRetrieve.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (preparedStatementInsert != null)
{
try
{
preparedStatementInsert.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (resultSet != null)
{
try
{
resultSet.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
public boolean updatePlayerCountInDatabase(int players)
{
PreparedStatement preparedStatement = null;
try
{
if (_connection == null || _connection.isClosed())
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
preparedStatement = _connection.prepareStatement(UPDATE_PLAYER_COUNT, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setInt(1, players);
preparedStatement.setInt(2, _maxPlayers);
preparedStatement.setInt(3, (int) ((Runtime.getRuntime().maxMemory() - Runtime.getRuntime().freeMemory()) / 1048576));
preparedStatement.setInt(4, (int) (Runtime.getRuntime().maxMemory() / 1048576));
preparedStatement.setInt(5, _id);
int affectedRows = preparedStatement.executeUpdate();
if (affectedRows == 0)
{
throw new SQLException("Updating bungee server player count failed, no rows affected.");
}
return true;
}
catch (Exception exception)
{
exception.printStackTrace();
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return updatePlayerCountInDatabase(players);
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
}

View File

@ -0,0 +1,78 @@
package mineplex.bungee.status;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
import net.md_5.bungee.api.config.ListenerInfo;
import net.md_5.bungee.api.plugin.Plugin;
public class InternetStatus implements Runnable
{
private Plugin _plugin;
private StatusRepository _repository;
public InternetStatus(Plugin plugin)
{
_plugin = plugin;
ListenerInfo listenerInfo = _plugin.getProxy().getConfigurationAdapter().getListeners().iterator().next();
boolean us = !new File("eu.dat").exists();
String address = listenerInfo.getHost().getAddress().getHostAddress() + ":" + listenerInfo.getHost().getPort();
_repository = new StatusRepository(address, us);
_repository.initialize();
_plugin.getProxy().getScheduler().schedule(_plugin, this, 1L, 1L, TimeUnit.MINUTES);
}
@Override
public void run()
{
_repository.updateOnlineStatus(isOnline());
}
private boolean isOnline()
{
if (testUrl("www.google.com"))
return true;
else if (testUrl("www.espn.com"))
return true;
else if (testUrl("www.bing.com"))
return true;
return false;
}
private boolean testUrl(String url)
{
Socket socket = null;
boolean reachable = false;
try
{
socket = new Socket(url, 80);
reachable = true;
}
catch (Exception e)
{
// Meh i don't care
}
finally
{
if (socket != null)
{
try
{
socket.close();
}
catch (IOException e)
{
}
}
}
return reachable;
}
}

View File

@ -0,0 +1,120 @@
package mineplex.bungee.status;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class StatusRepository
{
private String _connectionString = "jdbc:mysql://db.mineplex.com:3306/BungeeServers?autoReconnect=true&failOverReadOnly=false&maxReconnects=10";
private String _userName = "root";
private String _password = "tAbechAk3wR7tuTh";
private String _address;
private boolean _us;
private static String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS bungeeOnlineStatus (id INT NOT NULL AUTO_INCREMENT, address VARCHAR(40), online BOOLEAN NOT NULL DEFAULT 0, updated LONG, us BOOLEAN NOT NULL DEFAULT 1, lastOnline LONG, PRIMARY KEY (id), UNIQUE INDEX addressIndex(address));";
private static String INSERT_SERVER = "INSERT INTO bungeeOnlineStatus (address, online, us, updated) values(?, ?, ?, now()) ON DUPLICATE KEY UPDATE online = VALUES(online), updated = VALUES(updated);";
private static String INSERT_ONLINE_SERVER = "INSERT INTO bungeeOnlineStatus (address, online, us, updated, lastOnline) values(?, ?, ?, now(), now()) ON DUPLICATE KEY UPDATE online = VALUES(online), updated = VALUES(updated), lastOnline = VALUES(lastOnline);";
public StatusRepository(String address, boolean us)
{
_address = address;
_us = us;
}
public void initialize()
{
Connection connection = null;
PreparedStatement preparedStatement = null;
try
{
connection = DriverManager.getConnection(_connectionString, _userName, _password);
// Create table
preparedStatement = connection.prepareStatement(CREATE_TABLE);
preparedStatement.execute();
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (connection != null)
{
try
{
connection.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
public void updateOnlineStatus(boolean online)
{
Connection connection = null;
PreparedStatement preparedStatement = null;
try
{
connection = DriverManager.getConnection(_connectionString, _userName, _password);
preparedStatement = connection.prepareStatement(online ? INSERT_ONLINE_SERVER : INSERT_SERVER);
preparedStatement.setString(1, _address);
preparedStatement.setBoolean(2, online);
preparedStatement.setBoolean(3, _us);
preparedStatement.executeUpdate();
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (connection != null)
{
try
{
connection.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
}

View File

@ -1,7 +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 kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="var" path="REPO_DIR/Plugins/bin/craftbukkit.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -11,7 +11,7 @@ public enum Rank
OWNER("Owner", ChatColor.DARK_RED),
DEVELOPER("Dev", ChatColor.RED),
ADMIN("Admin", ChatColor.RED),
SENIOR_MODERATOR("Sr.Mod", ChatColor.GOLD),
SNR_MODERATOR("SnrMod", ChatColor.GOLD),
MODERATOR("Mod", ChatColor.GOLD),
HELPER("Helper", ChatColor.GREEN),
MAPDEV("Mapper", ChatColor.BLUE),

View File

@ -13,7 +13,9 @@ import net.minecraft.server.v1_7_R3.Blocks;
import net.minecraft.server.v1_7_R3.ChunkCoordIntPair;
import net.minecraft.server.v1_7_R3.ChunkSection;
import net.minecraft.server.v1_7_R3.EnumSkyBlock;
import net.minecraft.server.v1_7_R3.ExceptionWorldConflict;
import net.minecraft.server.v1_7_R3.IContainer;
import net.minecraft.server.v1_7_R3.IProgressUpdate;
import net.minecraft.server.v1_7_R3.MinecraftServer;
import net.minecraft.server.v1_7_R3.PacketPlayOutMapChunkBulk;
import net.minecraft.server.v1_7_R3.PacketPlayOutMultiBlockChange;
@ -135,12 +137,14 @@ public class MapUtil
public static void ChunkBlockChange(Location location, int id, byte data)
{
ChunkBlockChange(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), id, data);
ChunkBlockChange(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), id,
data);
}
public static void ChunkBlockChange(World world, int x, int y, int z, int id, byte data)
{
if (changeChunkBlock(x & 15, y, z & 15, ((CraftWorld) world).getHandle().getChunkAt(x >> 4, z >> 4), Block.e(id), data))
{
if (changeChunkBlock(x & 15, y, z & 15, ((CraftWorld) world).getHandle().getChunkAt(x >> 4, z >> 4),
Block.e(id), data))
{
((CraftWorld) world).getHandle().notify(x, y, z);
}
@ -175,13 +179,27 @@ public class MapUtil
public static void UnloadWorld(JavaPlugin plugin, World world)
{
world.setAutoSave(false);
UnloadWorld(plugin, world, false);
}
for (Entity entity : world.getEntities())
public static void UnloadWorld(JavaPlugin plugin, World world, boolean save)
{
if (save)
{
entity.remove();
try
{
((CraftWorld) world).getHandle().save(true, (IProgressUpdate) null);
}
catch (ExceptionWorldConflict e)
{
e.printStackTrace();
}
((CraftWorld) world).getHandle().saveLevel();
}
world.setAutoSave(save);
CraftServer server = (CraftServer) plugin.getServer();
CraftWorld craftWorld = (CraftWorld) world;
@ -190,6 +208,11 @@ public class MapUtil
Iterator<net.minecraft.server.v1_7_R3.Chunk> chunkIterator = ((CraftWorld) world).getHandle().chunkProviderServer.chunks
.values().iterator();
for (Entity entity : world.getEntities())
{
entity.remove();
}
while (chunkIterator.hasNext())
{
net.minecraft.server.v1_7_R3.Chunk chunk = chunkIterator.next();

View File

@ -1,40 +0,0 @@
package mineplex.core.common.util;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
public class TimeUtil
{
private static List<Entry<String, Long>> _timingList = new ArrayList<Entry<String, Long>>();
private static Object _timingLock = new Object();
public static void start(String title)
{
synchronized(_timingLock)
{
_timingList.add(new AbstractMap.SimpleEntry<String, Long>(title, System.currentTimeMillis()));
}
}
public static void stop()
{
synchronized(_timingLock)
{
Collections.reverse(_timingList);
for (Iterator<Entry<String, Long>> iterator = _timingList.iterator(); iterator.hasNext();)
{
Entry<String, Long> entry = iterator.next();
System.out.println(entry.getKey()+ " took " + (System.currentTimeMillis() - entry.getValue()) + "ms");
iterator.remove();
}
Collections.reverse(_timingList);
}
}
}

View File

@ -544,6 +544,11 @@ public class UtilEnt
}
public static boolean CreatureMoveFast(Entity ent, Location target, float speed)
{
return CreatureMoveFast(ent, target, speed, true);
}
public static boolean CreatureMoveFast(Entity ent, Location target, float speed, boolean slow)
{
if (!(ent instanceof Creature))
return false;

View File

@ -59,5 +59,19 @@ public class UtilMath
return a.subtract(b).length();
}
public static double offsetSquared(Entity a, Entity b)
{
return offsetSquared(a.getLocation(), b.getLocation());
}
public static double offsetSquared(Location a, Location b)
{
return offsetSquared(a.toVector(), b.toVector());
}
public static double offsetSquared(Vector a, Vector b)
{
return a.distanceSquared(b);
}
}

View File

@ -172,7 +172,7 @@ public class UtilPlayer
for (String cur : matches)
matchString += cur + " ";
if (matchString.length() > 1)
matchString = matchString.substring(0 , matchString.length() - 2);
matchString = matchString.substring(0 , matchString.length() - 1);
message(caller, F.main("Offline Player Search", "" +
C.mBody + "Matches [" +

View File

@ -83,11 +83,25 @@ public class UtilTime
else type = TimeUnit.DAYS;
}
if (type == TimeUnit.DAYS) return UtilMath.trim(trim, (time)/86400000d) + " Days";
if (type == TimeUnit.HOURS) return UtilMath.trim(trim, (time)/3600000d) + " Hours";
if (type == TimeUnit.MINUTES) return UtilMath.trim(trim, (time)/60000d) + " Minutes";
if (type == TimeUnit.SECONDS) return UtilMath.trim(trim, (time)/1000d) + " Seconds";
else return UtilMath.trim(trim, time) + " Milliseconds";
if (trim == 0)
{
if (type == TimeUnit.DAYS) return UtilMath.trim(trim, (time)/86400000d) + " Days";
if (type == TimeUnit.HOURS) return UtilMath.trim(trim, (time)/3600000d) + " Hours";
if (type == TimeUnit.MINUTES) return UtilMath.trim(trim, (time)/60000d) + " Minutes";
if (type == TimeUnit.SECONDS) return (int)UtilMath.trim(trim, (time)/1000d) + " Seconds";
else return (int)UtilMath.trim(trim, time) + " Milliseconds";
}
else
{
if (type == TimeUnit.DAYS) return UtilMath.trim(trim, (time)/86400000d) + " Days";
if (type == TimeUnit.HOURS) return UtilMath.trim(trim, (time)/3600000d) + " Hours";
if (type == TimeUnit.MINUTES) return UtilMath.trim(trim, (time)/60000d) + " Minutes";
if (type == TimeUnit.SECONDS) return UtilMath.trim(trim, (time)/1000d) + " Seconds";
else return UtilMath.trim(trim, time) + " Milliseconds";
}
}
public static boolean elapsed(long from, long required)

View File

@ -6,11 +6,154 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class ZipUtil
{
private static void getFileList(List<String> fileList, String sourceFolder, File node)
{
// add file only
if (node.isFile())
{
fileList.add(generateZipEntry(sourceFolder, node.getAbsoluteFile().toString()));
}
if (node.isDirectory())
{
String[] subNote = node.list();
for (String filename : subNote)
{
getFileList(fileList, sourceFolder, new File(node, filename));
}
}
}
private static String generateZipEntry(String sourceFolder, String file)
{
System.out.println(sourceFolder + " " + file);
return file.substring(sourceFolder.length() + 1, file.length());
}
public static void ZipFolders(String sourceFolder, String zipFilename, List<String> folders, List<String> files)
{
ZipOutputStream zipOutputStream = null;
FileOutputStream fileOutputStream = null;
FileInputStream fileInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
List<String> fileList = new ArrayList<String>();
byte[] buffer = new byte[2048];
try
{
fileOutputStream = new FileOutputStream(zipFilename);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
zipOutputStream = new ZipOutputStream(bufferedOutputStream);
ZipEntry entry;
for (String file : files)
{
fileList.add(generateZipEntry(sourceFolder, new File(file).getAbsoluteFile().toString()));
}
for (String folder : folders)
{
getFileList(fileList, sourceFolder, new File(folder));
}
for (String file : fileList)
{
entry = new ZipEntry(file);
zipOutputStream.putNextEntry(entry);
fileInputStream = new FileInputStream(sourceFolder + File.separator + file);
int len;
while ((len = fileInputStream.read(buffer)) > 0)
{
zipOutputStream.write(buffer, 0, len);
}
fileInputStream.close();
}
zipOutputStream.flush();
zipOutputStream.close();
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
if (fileInputStream != null)
{
try
{
fileInputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (bufferedOutputStream != null)
{
try
{
bufferedOutputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (zipOutputStream != null)
{
try
{
zipOutputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (fileOutputStream != null)
{
try
{
fileOutputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (bufferedOutputStream != null)
{
try
{
bufferedOutputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
public static void UnzipToDirectory(String zipFilePath, String outputDirectory)
{
FileInputStream fileInputStream = null;
@ -18,96 +161,96 @@ public class ZipUtil
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
BufferedInputStream bufferedInputStream = null;
try
{
fileInputStream = new FileInputStream(zipFilePath);
bufferedInputStream = new BufferedInputStream(fileInputStream);
zipInputStream = new ZipInputStream(bufferedInputStream);
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null)
{
int size;
byte[] buffer = new byte[2048];
fileOutputStream = new FileOutputStream(outputDirectory + File.separator + entry.getName());
bufferedOutputStream = new BufferedOutputStream(fileOutputStream, buffer.length);
while ((size = zipInputStream.read(buffer, 0, buffer.length)) != -1)
{
bufferedOutputStream.write(buffer, 0, size);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
}
zipInputStream.close();
bufferedInputStream.close();
fileInputStream.close();
}
catch (IOException e)
catch (IOException e)
{
e.printStackTrace();
if (fileInputStream != null)
{
try
try
{
fileInputStream.close();
}
catch (IOException e1)
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (bufferedInputStream != null)
{
try
try
{
bufferedInputStream.close();
}
catch (IOException e1)
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (zipInputStream != null)
{
try
try
{
zipInputStream.close();
}
catch (IOException e1)
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (fileOutputStream != null)
{
try
try
{
fileOutputStream.close();
}
catch (IOException e1)
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (bufferedOutputStream != null)
{
try
try
{
bufferedOutputStream.close();
}
catch (IOException e1)
}
catch (IOException e1)
{
e1.printStackTrace();
}

View File

@ -1,7 +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 kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/httpcore-4.2.jar"/>
<classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/httpclient-4.2.jar"/>
<classpathentry kind="var" path="REPO_DIR/Plugins/Libraries/commons-codec-1.6.jar"/>

View File

@ -1,16 +0,0 @@
package mineplex.core;
import org.bukkit.Server;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public interface INautilusPlugin
{
JavaPlugin GetPlugin();
String GetWebServerAddress();
Server GetRealServer();
PluginManager GetPluginManager();
}

View File

@ -2,19 +2,25 @@ package mineplex.core.account;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.UUID;
import mineplex.core.MiniPlugin;
import mineplex.core.account.command.UpdateRank;
import mineplex.core.account.event.AsyncClientLoadEvent;
import mineplex.core.account.event.ClientUnloadEvent;
import mineplex.core.account.event.ClientWebResponseEvent;
import mineplex.core.account.event.RetrieveClientInformationEvent;
import mineplex.core.account.repository.AccountRepository;
import mineplex.core.account.repository.MysqlAccountRepository;
import mineplex.core.account.repository.token.ClientToken;
import mineplex.core.common.Rank;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.logger.Logger;
import mineplex.core.timing.TimingManager;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
@ -24,7 +30,6 @@ import org.bukkit.craftbukkit.libs.com.google.gson.Gson;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result;
import org.bukkit.event.player.PlayerKickEvent;
@ -32,37 +37,36 @@ import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class CoreClientManager implements Listener
public class CoreClientManager extends MiniPlugin
{
private static CoreClientManager _instance;
private JavaPlugin _plugin;
private AccountRepository _repository;
private MysqlAccountRepository _mysqlRepository;
private NautHashMap<String, CoreClient> _clientList;
private HashSet<String> _duplicateLoginGlitchPreventionList;
private Object _clientLock = new Object();
protected CoreClientManager(JavaPlugin plugin, String webServer)
public CoreClientManager(JavaPlugin plugin, String webServer)
{
_instance = this;
super("Client Manager", plugin);
_plugin = plugin;
_repository = new AccountRepository(webServer);
_mysqlRepository = new MysqlAccountRepository(plugin);
_clientList = new NautHashMap<String, CoreClient>();
_duplicateLoginGlitchPreventionList = new HashSet<String>();
_plugin.getServer().getPluginManager().registerEvents(this, _plugin);
}
public static CoreClientManager Initialize(JavaPlugin plugin, String webServer)
public AccountRepository getRepository()
{
if (_instance == null)
{
_instance = new CoreClientManager(plugin, webServer);
}
return _instance;
return _repository;
}
@Override
public void AddCommands()
{
AddCommand(new UpdateRank(this));
}
public CoreClient Add(String name)
@ -118,6 +122,7 @@ public class CoreClientManager implements Listener
@EventHandler(priority = EventPriority.LOWEST)
public void AsyncLogin(AsyncPlayerPreLoginEvent event)
{
TimingManager.start(event.getName() + " logging in ASYNC.");
try
{
LoadClient(Add(event.getName()), event.getUniqueId(), event.getAddress().getHostAddress());
@ -141,6 +146,8 @@ public class CoreClientManager implements Listener
event.disallow(Result.KICK_WHITELIST, "You are not whitelisted my friend.");
}
TimingManager.stop(event.getName() + " logging in ASYNC.");
}
private void LoadClient(CoreClient client, UUID uuid, String ipAddress)
@ -155,6 +162,8 @@ public class CoreClientManager implements Listener
client.SetAccountId(token.AccountId);
client.SetRank(Rank.valueOf(token.Rank));
_mysqlRepository.login(uuid.toString(), client.GetPlayerName());
// JSON sql response
Bukkit.getServer().getPluginManager().callEvent(new ClientWebResponseEvent(response));
@ -173,10 +182,18 @@ public class CoreClientManager implements Listener
System.out.println("Error running RetrieveClientInformationEvent" + exception.getMessage());
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void LoginTiming(PlayerLoginEvent event)
{
TimingManager.stop(event.getPlayer().getName() + " logging in SYNC.");
}
@EventHandler(priority = EventPriority.LOWEST)
public void Login(PlayerLoginEvent event)
{
TimingManager.start(event.getPlayer().getName() + " logging in SYNC.");
synchronized(_clientLock)
{
if (!_clientList.containsKey(event.getPlayer().getName()))
@ -188,7 +205,10 @@ public class CoreClientManager implements Listener
CoreClient client = Get(event.getPlayer().getName());
if (client == null || client.GetRank() == null)
{
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "There was an error logging you in. Please reconncet.");
return;
}
client.SetPlayer(event.getPlayer());
@ -202,7 +222,7 @@ public class CoreClientManager implements Listener
return;
}
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "Server Full > Purchase Ultra at www.mineplex.com/shop");
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "This server is full and no longer accepts players.");
}
}
@ -249,6 +269,50 @@ public class CoreClientManager implements Listener
}, name, rank, perm);
}
public void checkPlayerName(final Player caller, final String playerName, final Callback<Boolean> callback)
{
_repository.MatchPlayerName(new Callback<List<String>>()
{
public void run(List<String> matches)
{
boolean matchedExact = false;
for (String match : matches)
{
if (match.equalsIgnoreCase(playerName))
{
matchedExact = true;
}
}
if (matchedExact)
{
for (Iterator<String> matchIterator = matches.iterator(); matchIterator.hasNext();)
{
if (!matchIterator.next().equalsIgnoreCase(playerName))
{
matchIterator.remove();
}
}
}
UtilPlayer.searchOffline(matches, new Callback<String>()
{
public void run(final String target)
{
if (target == null)
{
callback.run(false);
return;
}
callback.run(true);
}
}, caller, playerName, true);
}
}, playerName);
}
@EventHandler
public void cleanGlitchedClients(UpdateEvent event)
{

View File

@ -0,0 +1,104 @@
package mineplex.core.account.command;
import java.util.Iterator;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import mineplex.core.account.CoreClientManager;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
public class UpdateRank extends CommandBase<CoreClientManager>
{
public UpdateRank(CoreClientManager plugin)
{
super(plugin, Rank.ADMIN, "updateRank");
}
@Override
public void Execute(final Player caller, String[] args)
{
if (args == null)
{
UtilPlayer.message(caller, F.main(Plugin.GetName(), "/" + AliasUsed + " joeschmo MODERATOR"));
}
else
{
if (args.length == 0)
{
UtilPlayer.message(caller, F.main(Plugin.GetName(), "Player argument missing."));
return;
}
final String playerName = args[0];
Rank tempRank = null;
try
{
tempRank = Rank.valueOf(args[1]);
}
catch (Exception ex)
{
UtilPlayer.message(caller, F.main(Plugin.GetName(), ChatColor.RED + "" + ChatColor.BOLD + "Invalid rank!"));
return;
}
final Rank rank = tempRank;
if (rank == Rank.MODERATOR || rank == Rank.HELPER || rank == Rank.ALL || rank == Rank.MAPDEV)
{
Plugin.getRepository().MatchPlayerName(new Callback<List<String>>()
{
public void run(List<String> matches)
{
boolean matchedExact = false;
for (String match : matches)
{
if (match.equalsIgnoreCase(playerName))
{
matchedExact = true;
}
}
if (matchedExact)
{
for (Iterator<String> matchIterator = matches.iterator(); matchIterator.hasNext();)
{
if (!matchIterator.next().equalsIgnoreCase(playerName))
{
matchIterator.remove();
}
}
}
UtilPlayer.searchOffline(matches, new Callback<String>()
{
public void run(final String target)
{
if (target == null)
{
return;
}
Plugin.getRepository().SaveRank(new Callback<Rank>()
{
public void run(Rank rank)
{
caller.sendMessage(F.main(Plugin.GetName(), target + "'s rank has been updated to " + rank.Name + "!"));
}
}, target, rank, true);
}
}, caller, playerName, true);
}
}, playerName);
}
}
}
}

View File

@ -1,7 +1,10 @@
package mineplex.core.account.repository;
import java.util.List;
import java.util.UUID;
import org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken;
import mineplex.core.account.repository.token.LoginToken;
import mineplex.core.account.repository.token.RankUpdateToken;
import mineplex.core.common.Rank;
@ -37,4 +40,18 @@ public class AccountRepository
new AsyncJsonWebCall(_webAddress + "PlayerAccount/RankUpdate").Execute(Rank.class, callback, token);
}
public void MatchPlayerName(final Callback<List<String>> callback, final String userName)
{
Thread asyncThread = new Thread(new Runnable()
{
public void run()
{
List<String> tokenList = new JsonWebCall(_webAddress + "PlayerAccount/GetMatches").Execute(new TypeToken<List<String>>(){}.getType(), userName);
callback.run(tokenList);
}
});
asyncThread.start();
}
}

View File

@ -2,39 +2,30 @@ package mineplex.core.account.repository;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.mysql.RepositoryBase;
import mineplex.core.database.RepositoryBase;
import mineplex.core.database.column.ColumnVarChar;
public class MysqlAccountRepository extends RepositoryBase
{
private static String CREATE_ACCOUNT_TABLE = "CREATE TABLE IF NOT EXISTS Accounts (id INT NOT NULL AUTO_INCREMENT, name VARCHAR(40), gems INT, rank VARCHAR(40), rankPerm BOOL, rankExpire LONG, lastLogin LONG, totalPlayTime LONG, PRIMARY KEY (id));";
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 = "INSERT INTO accounts (uuid, name, lastLogin) values(?, ?, now()) ON DUPLICATE KEY UPDATE name=VALUES(name), lastLogin=VALUES(lastLogin);";
public MysqlAccountRepository(JavaPlugin plugin)
{
super(plugin);
super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh");
}
/*
public String GetClient(String name, String ipAddress)
{
return "";
}
public void SaveRank(Callback<Rank> callback, String name, Rank rank, boolean perm)
{
RankUpdateToken token = new RankUpdateToken();
token.Name = name;
token.Rank = rank.toString();
token.Perm = perm;
//new AsyncJsonWebCall(_webAddress + "PlayerAccount/RankUpdate").Execute(Rank.class, callback, token);
}
*/
@Override
protected void initialize()
{
executeQuery(CREATE_ACCOUNT_TABLE);
executeUpdate(CREATE_ACCOUNT_TABLE);
}
@Override
protected void update() { }
public void login(String uuid, String name)
{
executeUpdate(ACCOUNT_LOGIN, new ColumnVarChar("uuid", 100, uuid), new ColumnVarChar("name", 40, name));
}
}

View File

@ -8,4 +8,5 @@ public class ClientToken
public int EconomyBalance;
public AccountToken AccountToken;
public long LastLogin;
}

View File

@ -351,7 +351,7 @@ public class AntiHack extends MiniPlugin
player.kickPlayer(
C.cGold + "Mineplex Anti-Cheat" + "\n" +
C.cWhite + "You were kicked for suspicious movement." + "\n" +
C.cWhite + "Cheating will result in a " + C.cRed + "Permanent Ban" + C.cWhite + "." + "\n" +
C.cWhite + "Cheating may result in a " + C.cRed + "Permanent Ban" + C.cWhite + "." + "\n" +
C.cWhite + "If you were not cheating, you will not be banned."
);

View File

@ -18,10 +18,10 @@ public class CommandCenter implements Listener
protected CoreClientManager ClientManager;
protected NautHashMap<String, ICommand> Commands;
public static void Initialize(JavaPlugin plugin, CoreClientManager clientManager)
public static void Initialize(JavaPlugin plugin)
{
if (Instance == null)
Instance = new CommandCenter(plugin, clientManager);
Instance = new CommandCenter(plugin);
}
public CoreClientManager GetClientManager()
@ -29,14 +29,18 @@ public class CommandCenter implements Listener
return ClientManager;
}
private CommandCenter(JavaPlugin instance, CoreClientManager manager)
private CommandCenter(JavaPlugin instance)
{
Plugin = instance;
ClientManager = manager;
Commands = new NautHashMap<String, ICommand>();
Plugin.getServer().getPluginManager().registerEvents(this, Plugin);
}
public void setClientManager(CoreClientManager clientManager)
{
ClientManager = clientManager;
}
@EventHandler
public void OnPlayerCommandPreprocess(PlayerCommandPreprocessEvent event)
{

View File

@ -0,0 +1,232 @@
package mineplex.core.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import mineplex.core.database.column.Column;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
public abstract class RepositoryBase
{
protected static Object _connectionLock = new Object();
private Connection _connection = null;
private String _connectionString;
private String _userName;
private String _password;
public RepositoryBase(JavaPlugin plugin, String connectionString, String username, String password)
{
_connectionString = connectionString;
_userName = username;
_password = password;
Bukkit.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable()
{
public void run()
{
synchronized (_connectionLock)
{
initialize();
update();
}
}
});
}
protected abstract void initialize();
protected abstract void update();
protected Connection getConnection()
{
try
{
if (_connection == null || !_connection.isValid(1))
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
catch (SQLException e)
{
e.printStackTrace();
}
return _connection;
}
protected int executeUpdate(String query, Column<?>...columns)
{
Connection connection = null;
PreparedStatement preparedStatement = null;
int affectedRows = 0;
try
{
connection = DriverManager.getConnection(_connectionString, _userName, _password);
preparedStatement = connection.prepareStatement(query);
for (int i=0; i < columns.length; i++)
{
columns[i].setValue(preparedStatement, i+1);
}
affectedRows = preparedStatement.executeUpdate();
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (connection != null)
{
try
{
connection.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
return affectedRows;
}
protected void executeQuery(PreparedStatement statement, ResultSetCallable callable, Column<?>...columns)
{
ResultSet resultSet = null;
try
{
for (int i=0; i < columns.length; i++)
{
columns[i].setValue(statement, i+1);
}
resultSet = statement.executeQuery();
callable.processResultSet(resultSet);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (resultSet != null)
{
try
{
resultSet.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
protected void executeQuery(String query, ResultSetCallable callable, Column<?>...columns)
{
Connection connection = null;
PreparedStatement preparedStatement = null;
try
{
connection = DriverManager.getConnection(_connectionString, _userName, _password);
preparedStatement = connection.prepareStatement(query);
executeQuery(preparedStatement, callable, columns);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (connection != null)
{
try
{
connection.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
protected int executeUpdate(PreparedStatement preparedStatement, Column<?>...columns)
{
Connection connection = null;
int affectedRows = 0;
try
{
connection = DriverManager.getConnection(_connectionString, _userName, _password);
for (int i=0; i < columns.length; i++)
{
columns[i].setValue(preparedStatement, i+1);
}
affectedRows = preparedStatement.executeUpdate();
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (connection != null)
{
try
{
connection.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
return affectedRows;
}
}

View File

@ -0,0 +1,9 @@
package mineplex.core.database;
import java.sql.ResultSet;
import java.sql.SQLException;
public interface ResultSetCallable
{
public void processResultSet(ResultSet resultSet) throws SQLException;
}

View File

@ -1,4 +1,4 @@
package mineplex.core.stats;
package mineplex.core.database;
import java.sql.Connection;
import java.sql.DriverManager;
@ -11,7 +11,8 @@ import java.util.Iterator;
import java.util.List;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.stats.column.Column;
import mineplex.core.database.column.Column;
import mineplex.core.stats.Row;
public class Table
{

View File

@ -1,5 +1,6 @@
package mineplex.core.stats.column;
package mineplex.core.database.column;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@ -23,5 +24,7 @@ public abstract class Column<Type>
public abstract Type getValue(ResultSet resultSet) throws SQLException;
public abstract void setValue(PreparedStatement preparedStatement, int columnNumber) throws SQLException;
public abstract Column<Type> clone();
}

View File

@ -1,5 +1,6 @@
package mineplex.core.stats.column;
package mineplex.core.database.column;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@ -27,6 +28,12 @@ public class ColumnInt extends Column<Integer>
{
return resultSet.getInt(Name);
}
@Override
public void setValue(PreparedStatement preparedStatement, int columnNumber) throws SQLException
{
preparedStatement.setInt(columnNumber, Value);
}
@Override
public ColumnInt clone()

View File

@ -1,5 +1,6 @@
package mineplex.core.stats.column;
package mineplex.core.database.column;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@ -27,6 +28,12 @@ public class ColumnLong extends Column<Long>
{
return resultSet.getLong(Name);
}
@Override
public void setValue(PreparedStatement preparedStatement, int columnNumber) throws SQLException
{
preparedStatement.setLong(columnNumber, Value);
}
@Override
public ColumnLong clone()

View File

@ -1,5 +1,6 @@
package mineplex.core.stats.column;
package mineplex.core.database.column;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@ -30,6 +31,12 @@ public class ColumnVarChar extends Column<String>
{
return resultSet.getString(Name);
}
@Override
public void setValue(PreparedStatement preparedStatement, int columnNumber) throws SQLException
{
preparedStatement.setString(columnNumber, Value);
}
@Override
public ColumnVarChar clone()

View File

@ -45,6 +45,7 @@ import mineplex.core.disguise.disguises.DisguisePlayer;
import mineplex.core.packethandler.IPacketRunnable;
import mineplex.core.packethandler.PacketHandler;
import mineplex.core.packethandler.PacketVerifier;
import mineplex.core.timing.TimingManager;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
@ -119,6 +120,10 @@ public class DisguiseManager extends MiniPlugin implements IPacketRunnable
if (!_spawnPacketMap.containsKey(entity.getEntityId()))
return;
_spawnPacketMap.remove(entity.getEntityId());
_movePacketMap.remove(entity.getEntityId());
_moveTempMap.remove(entity.getEntityId());
for (Player player : Bukkit.getOnlinePlayers())
{
if (entity == player)
@ -129,6 +134,7 @@ public class DisguiseManager extends MiniPlugin implements IPacketRunnable
if (entity instanceof Player)
{
player.hidePlayer((Player)entity);
player.showPlayer((Player)entity);
}
else
@ -136,10 +142,6 @@ public class DisguiseManager extends MiniPlugin implements IPacketRunnable
entityPlayer.playerConnection.sendPacket(new PacketPlayOutSpawnEntityLiving(((CraftLivingEntity)entity).getHandle()));
}
}
_spawnPacketMap.remove(entity.getEntityId());
_movePacketMap.remove(entity.getEntityId());
_moveTempMap.remove(entity.getEntityId());
}
public void reApplyDisguise(final DisguiseBase disguise)
@ -233,6 +235,7 @@ public class DisguiseManager extends MiniPlugin implements IPacketRunnable
if (event.getType() != UpdateType.SEC)
return;
TimingManager.startTotal("Teleport Disguises");
for (Player player : Bukkit.getOnlinePlayers())
{
for (Player otherPlayer : Bukkit.getOnlinePlayers())
@ -244,6 +247,7 @@ public class DisguiseManager extends MiniPlugin implements IPacketRunnable
((CraftPlayer)player).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityTeleport(((CraftPlayer)otherPlayer).getHandle()));
}
}
TimingManager.stopTotal("Teleport Disguises");
}
public void clearDisguises()

View File

@ -1,10 +1,12 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public abstract class DisguiseAgeable extends DisguiseCreature
{
public DisguiseAgeable(org.bukkit.entity.Entity entity)
public DisguiseAgeable(EntityType disguiseType, org.bukkit.entity.Entity entity)
{
super(entity);
super(disguiseType, entity);
DataWatcher.a(12, new Integer(0));
}

View File

@ -1,9 +1,11 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public abstract class DisguiseAnimal extends DisguiseAgeable
{
public DisguiseAnimal(org.bukkit.entity.Entity entity)
public DisguiseAnimal(EntityType disguiseType, org.bukkit.entity.Entity entity)
{
super(entity);
super(disguiseType, entity);
}
}

View File

@ -1,10 +1,12 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguiseBat extends DisguiseAnimal
{
public DisguiseBat(org.bukkit.entity.Entity entity)
{
super(entity);
super(EntityType.BAT, entity);
DataWatcher.a(16, new Byte((byte)0));
}
@ -23,12 +25,6 @@ public class DisguiseBat extends DisguiseAnimal
DataWatcher.watch(16, Byte.valueOf((byte)(i & 0xFFFFFFFE)));
}
@Override
protected int GetEntityTypeId()
{
return 65;
}
public String getHurtSound()
{
return "mob.bat.hurt";

View File

@ -1,19 +1,15 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguiseBlaze extends DisguiseMonster
{
public DisguiseBlaze(org.bukkit.entity.Entity entity)
{
super(entity);
super(EntityType.BLAZE, entity);
DataWatcher.a(16, new Byte((byte)0));
}
@Override
protected int GetEntityTypeId()
{
return 61;
}
public boolean bT()
{

View File

@ -1,10 +1,12 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguiseCat extends DisguiseTameableAnimal
{
public DisguiseCat(org.bukkit.entity.Entity entity)
{
super(entity);
super(EntityType.OCELOT, entity);
DataWatcher.a(18, Byte.valueOf((byte)0));
}
@ -19,12 +21,6 @@ public class DisguiseCat extends DisguiseTameableAnimal
DataWatcher.watch(18, Byte.valueOf((byte)i));
}
@Override
protected int GetEntityTypeId()
{
return 98;
}
protected String getHurtSound()
{
return "mob.cat.hitt";

View File

@ -1,16 +1,12 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguiseChicken extends DisguiseAnimal
{
public DisguiseChicken(org.bukkit.entity.Entity entity)
{
super(entity);
}
@Override
protected int GetEntityTypeId()
{
return 93;
super(EntityType.CHICKEN, entity);
}
public String getHurtSound()

View File

@ -1,16 +1,12 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguiseCow extends DisguiseAnimal
{
public DisguiseCow(org.bukkit.entity.Entity entity)
{
super(entity);
}
@Override
protected int GetEntityTypeId()
{
return 92;
super(EntityType.COW, entity);
}
public String getHurtSound()

View File

@ -4,21 +4,30 @@ import net.minecraft.server.v1_7_R3.EnumEntitySize;
import net.minecraft.server.v1_7_R3.MathHelper;
import net.minecraft.server.v1_7_R3.Packet;
import net.minecraft.server.v1_7_R3.PacketPlayOutSpawnEntityLiving;
import org.bukkit.entity.*;
public abstract class DisguiseCreature extends DisguiseInsentient
{
public DisguiseCreature(org.bukkit.entity.Entity entity)
private final EntityType _disguiseType;
public DisguiseCreature(EntityType disguiseType, org.bukkit.entity.Entity entity)
{
super(entity);
_disguiseType = disguiseType;
}
protected abstract int GetEntityTypeId();
public EntityType getDisguiseType()
{
return _disguiseType;
}
@SuppressWarnings("deprecation")
public Packet GetSpawnPacket()
{
PacketPlayOutSpawnEntityLiving packet = new PacketPlayOutSpawnEntityLiving();
packet.a = Entity.getId();
packet.b = (byte) GetEntityTypeId();
packet.b = (byte) getDisguiseType().getTypeId();
packet.c = (int)EnumEntitySize.SIZE_2.a(Entity.locX);
packet.d = (int)MathHelper.floor(Entity.locY * 32.0D);
packet.e = (int)EnumEntitySize.SIZE_2.a(Entity.locZ);

View File

@ -1,20 +1,16 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguiseCreeper extends DisguiseMonster
{
public DisguiseCreeper(org.bukkit.entity.Entity entity)
{
super(entity);
super(EntityType.CREEPER, entity);
DataWatcher.a(16, Byte.valueOf((byte)-1));
DataWatcher.a(17, Byte.valueOf((byte)0));
}
@Override
protected int GetEntityTypeId()
{
return 50;
}
public boolean IsPowered()
{

View File

@ -5,12 +5,13 @@ import java.util.Arrays;
import net.minecraft.server.v1_7_R3.MobEffect;
import net.minecraft.server.v1_7_R3.MobEffectList;
import net.minecraft.server.v1_7_R3.PotionBrewer;
import org.bukkit.entity.*;
public class DisguiseEnderman extends DisguiseMonster
{
public DisguiseEnderman(org.bukkit.entity.Entity entity)
{
super(entity);
super(EntityType.ENDERMAN, entity);
DataWatcher.a(16, new Byte((byte)0));
DataWatcher.a(17, new Byte((byte)0));
@ -51,12 +52,6 @@ public class DisguiseEnderman extends DisguiseMonster
DataWatcher.watch(18, Byte.valueOf((byte)(flag ? 1 : 0)));
}
@Override
protected int GetEntityTypeId()
{
return 58;
}
protected String getHurtSound()
{
return "mob.endermen.hit";

View File

@ -1,9 +1,11 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public abstract class DisguiseGolem extends DisguiseCreature
{
public DisguiseGolem(org.bukkit.entity.Entity entity)
public DisguiseGolem(EntityType disguiseType, org.bukkit.entity.Entity entity)
{
super(entity);
super(disguiseType, entity);
}
}

View File

@ -1,12 +1,12 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.Horse;
import org.bukkit.entity.*;
public class DisguiseHorse extends DisguiseAnimal
{
public DisguiseHorse(org.bukkit.entity.Entity entity)
{
super(entity);
super(EntityType.HORSE, entity);
DataWatcher.a(16, Integer.valueOf(0));
DataWatcher.a(19, Byte.valueOf((byte) 0));
@ -15,12 +15,6 @@ public class DisguiseHorse extends DisguiseAnimal
DataWatcher.a(22, Integer.valueOf(0));
}
@Override
protected int GetEntityTypeId()
{
return 100;
}
public void setType(Horse.Variant horseType)
{
DataWatcher.watch(19, Byte.valueOf((byte) horseType.ordinal()));

View File

@ -1,19 +1,15 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguiseIronGolem extends DisguiseGolem
{
public DisguiseIronGolem(org.bukkit.entity.Entity entity)
{
super(entity);
super(EntityType.IRON_GOLEM, entity);
DataWatcher.a(16, Byte.valueOf((byte)0));
}
@Override
protected int GetEntityTypeId()
{
return 99;
}
public boolean bW()
{

View File

@ -1,9 +1,11 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public abstract class DisguiseMonster extends DisguiseCreature
{
public DisguiseMonster(org.bukkit.entity.Entity entity)
public DisguiseMonster(EntityType disguiseType, org.bukkit.entity.Entity entity)
{
super(entity);
super(disguiseType, entity);
}
}

View File

@ -1,16 +1,12 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguisePig extends DisguiseAnimal
{
public DisguisePig(org.bukkit.entity.Entity entity)
{
super(entity);
}
@Override
protected int GetEntityTypeId()
{
return 90;
super(EntityType.PIG, entity);
}
public String getHurtSound()

View File

@ -1,16 +1,12 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguisePigZombie extends DisguiseZombie
{
public DisguisePigZombie(org.bukkit.entity.Entity entity)
{
super(entity);
}
@Override
public int GetEntityTypeId()
{
return 57;
super(EntityType.PIG_ZOMBIE, entity);
}
protected String getHurtSound()

View File

@ -1,21 +1,16 @@
package mineplex.core.disguise.disguises;
import org.bukkit.DyeColor;
import org.bukkit.entity.*;
public class DisguiseSheep extends DisguiseAnimal
{
public DisguiseSheep(org.bukkit.entity.Entity entity)
{
super(entity);
super(EntityType.SHEEP, entity);
DataWatcher.a(16, new Byte((byte)0));
}
@Override
protected int GetEntityTypeId()
{
return 91;
}
public boolean isSheared()
{

View File

@ -1,21 +1,16 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
import org.bukkit.entity.Skeleton.SkeletonType;
public class DisguiseSkeleton extends DisguiseMonster
{
public DisguiseSkeleton(org.bukkit.entity.Entity entity)
{
super(entity);
super(EntityType.SKELETON, entity);
DataWatcher.a(13, Byte.valueOf((byte)0));
}
@Override
protected int GetEntityTypeId()
{
return 51;
}
public void SetSkeletonType(SkeletonType skeletonType)
{

View File

@ -1,15 +1,11 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguiseSnowman extends DisguiseGolem
{
public DisguiseSnowman(org.bukkit.entity.Entity entity)
{
super(entity);
}
@Override
protected int GetEntityTypeId()
{
return 97;
super(EntityType.SNOWMAN, entity);
}
}

View File

@ -1,15 +1,17 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguiseSpider extends DisguiseMonster
{
public DisguiseSpider(org.bukkit.entity.Entity entity)
{
super(entity);
DataWatcher.a(16, new Byte((byte)0));
super(EntityType.SPIDER, entity);
DataWatcher.a(16, new Byte((byte) 0));
}
public boolean bT()
public boolean bT()
{
return (DataWatcher.getByte(16) & 0x01) != 0;
}
@ -17,23 +19,17 @@ public class DisguiseSpider extends DisguiseMonster
public void a(boolean flag)
{
byte b0 = DataWatcher.getByte(16);
if (flag)
b0 = (byte)(b0 | 0x1);
if(flag)
b0 = (byte) (b0 | 0x1);
else
b0 = (byte)(b0 & 0xFFFFFFFE);
b0 = (byte) (b0 & 0xFFFFFFFE);
DataWatcher.watch(16, Byte.valueOf(b0));
}
@Override
protected int GetEntityTypeId()
protected String getHurtSound()
{
return 52;
return "mob.spider.say";
}
protected String getHurtSound()
{
return "mob.spider.say";
}
}

View File

@ -1,10 +1,12 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguiseSquid extends DisguiseMonster
{
public DisguiseSquid(org.bukkit.entity.Entity entity)
{
super(entity);
super(EntityType.SQUID, entity);
DataWatcher.a(16, new Byte((byte)0));
}
@ -26,12 +28,6 @@ public class DisguiseSquid extends DisguiseMonster
DataWatcher.watch(16, Byte.valueOf(b0));
}
@Override
protected int GetEntityTypeId()
{
return 94;
}
protected String getHurtSound()
{
return "damage.hit";

View File

@ -1,10 +1,12 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public abstract class DisguiseTameableAnimal extends DisguiseAnimal
{
public DisguiseTameableAnimal(org.bukkit.entity.Entity entity)
public DisguiseTameableAnimal(EntityType disguiseType, org.bukkit.entity.Entity entity)
{
super(entity);
super(disguiseType, entity);
DataWatcher.a(16, Byte.valueOf((byte)0));
DataWatcher.a(17, "");

View File

@ -0,0 +1,17 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguiseVillager extends DisguiseCreature
{
public DisguiseVillager(Entity entity)
{
super(EntityType.VILLAGER, entity);
}
@Override
protected String getHurtSound()
{
return "mob.villager.hit";
}
}

View File

@ -1,19 +1,15 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguiseWitch extends DisguiseMonster
{
public DisguiseWitch(org.bukkit.entity.Entity entity)
{
super(entity);
super(EntityType.WITCH, entity);
DataWatcher.a(21, Byte.valueOf((byte)0));
}
@Override
protected int GetEntityTypeId()
{
return 66;
}
public String getHurtSound()
{

View File

@ -1,12 +1,13 @@
package mineplex.core.disguise.disguises;
import net.minecraft.server.v1_7_R3.BlockCloth;
import org.bukkit.entity.*;
public class DisguiseWolf extends DisguiseTameableAnimal
{
public DisguiseWolf(org.bukkit.entity.Entity entity)
{
super(entity);
super(EntityType.WOLF, entity);
DataWatcher.a(18, new Float(20F));
DataWatcher.a(19, new Byte((byte)0));
@ -51,12 +52,6 @@ public class DisguiseWolf extends DisguiseTameableAnimal
return DataWatcher.getByte(19) == 1;
}
@Override
protected int GetEntityTypeId()
{
return 95;
}
protected String getHurtSound()
{
return "mob.wolf.hurt";

View File

@ -1,23 +1,22 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.Entity;
import org.bukkit.entity.*;
public class DisguiseZombie extends DisguiseMonster
{
public DisguiseZombie(Entity entity)
{
super(entity);
this(EntityType.ZOMBIE, entity);
}
public DisguiseZombie(EntityType disguiseType, Entity entity)
{
super(disguiseType, entity);
DataWatcher.a(12, Byte.valueOf((byte)0));
DataWatcher.a(13, Byte.valueOf((byte)0));
DataWatcher.a(14, Byte.valueOf((byte)0));
}
@Override
protected int GetEntityTypeId()
{
return 54;
}
public boolean IsBaby()
{

View File

@ -0,0 +1,154 @@
package mineplex.core.friend;
import net.minecraft.server.v1_7_R3.Packet;
import net.minecraft.server.v1_7_R3.PacketPlayOutPlayerInfo;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniClientPlugin;
import mineplex.core.account.event.RetrieveClientInformationEvent;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.friend.command.AddFriend;
import mineplex.core.friend.command.DeleteFriend;
import mineplex.core.friend.data.FriendData;
import mineplex.core.friend.data.FriendRepository;
import mineplex.core.friend.ui.FriendTabList;
import mineplex.core.packethandler.IPacketRunnable;
import mineplex.core.packethandler.PacketHandler;
import mineplex.core.packethandler.PacketVerifier;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
public class FriendManager extends MiniClientPlugin<FriendData> implements IPacketRunnable
{
private FriendRepository _repository;
private NautHashMap<Player, FriendTabList> _playerTabMap;
private boolean _sendingPackets = false;
public FriendManager(JavaPlugin plugin, PacketHandler packetHandler)
{
super("Friends", plugin);
_repository = new FriendRepository(plugin);
_playerTabMap = new NautHashMap<Player, FriendTabList>();
packetHandler.AddPacketRunnable(this);
}
@Override
public void AddCommands()
{
AddCommand(new AddFriend(this));
AddCommand(new DeleteFriend(this));
}
@Override
protected FriendData AddPlayer(String player)
{
return new FriendData();
}
@Override
protected void loadClientInformation(RetrieveClientInformationEvent event)
{
Set(event.getPlayerName(), _repository.loadClientInformation(event.getUniqueId()));
}
@EventHandler
public void updateTabLists(UpdateEvent event)
{
if (event.getType() != UpdateType.SEC)
return;
_sendingPackets = true;
for (Player player : Bukkit.getOnlinePlayers())
{
if (!_playerTabMap.containsKey(player) || !_playerTabMap.get(player).shouldUpdate())
continue;
_playerTabMap.get(player).refreshForPlayer(player);
}
_sendingPackets = false;
}
public void updateFriends(UpdateEvent event)
{
if (event.getType() != UpdateType.SLOW)
return;
Bukkit.getServer().getScheduler().runTaskAsynchronously(_plugin, new Runnable()
{
public void run()
{
final NautHashMap<String, FriendData> newData = _repository.getFriendsForAll(Bukkit.getOnlinePlayers());
Bukkit.getServer().getScheduler().runTask(_plugin, new Runnable()
{
public void run()
{
for (Player player : _playerTabMap.keySet())
{
if (newData.containsKey(player.getName()))
{
_playerTabMap.get(player).updateFriends(newData.get(player.getName()).Friends);
Get(player).Friends = newData.get(player.getName()).Friends;
}
}
}
});
}
});
}
@EventHandler
public void addFriendTab(PlayerJoinEvent event)
{
_playerTabMap.put(event.getPlayer(), new FriendTabList(Get(event.getPlayer().getName()).Friends));
_playerTabMap.get(event.getPlayer()).refreshForPlayer(event.getPlayer());
}
@EventHandler
public void removeFriendTab(PlayerQuitEvent event)
{
_playerTabMap.remove(event.getPlayer());
}
@Override
public boolean run(Packet packet, Player owner, PacketVerifier packetList)
{
if (packet instanceof PacketPlayOutPlayerInfo)
{
return _sendingPackets;
}
return true;
}
public void addFriend(final Player caller, final String name)
{
Bukkit.getServer().getScheduler().runTaskAsynchronously(GetPlugin(), new Runnable()
{
public void run()
{
_repository.addFriend(caller.getUniqueId().toString(), name);
}
});
}
public void removeFriend(final Player caller, final String name)
{
Bukkit.getServer().getScheduler().runTaskAsynchronously(GetPlugin(), new Runnable()
{
public void run()
{
_repository.removeFriend(caller.getUniqueId().toString(), name);
}
});
}
}

View File

@ -0,0 +1,43 @@
package mineplex.core.friend;
import java.util.Comparator;
import mineplex.core.friend.data.FriendStatus;
public class FriendSorter implements Comparator<FriendStatus>
{
public int compare(FriendStatus a, FriendStatus b)
{
if (a.Online && !b.Online)
{
return -1;
}
if (b.Online && !a.Online)
{
return 1;
}
// If online we sort by mutual
if (a.Online && b.Online)
{
if (a.Mutual && !b.Mutual)
return -1;
else if (b.Mutual && !a.Mutual)
return 1;
if (a.Name.compareTo(b.Name) > 0)
return -1;
else if (b.Name.compareTo(a.Name) > 0)
return 1;
}
if (a.LastSeenOnline < b.LastSeenOnline)
return -1;
if (b.LastSeenOnline < a.LastSeenOnline)
return 1;
return 0;
}
}

View File

@ -0,0 +1,37 @@
package mineplex.core.friend.command;
import org.bukkit.entity.Player;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.F;
import mineplex.core.friend.FriendManager;
public class AddFriend extends CommandBase<FriendManager>
{
public AddFriend(FriendManager plugin)
{
super(plugin, Rank.ALL, "friend");
}
@Override
public void Execute(final Player caller, final String[] args)
{
if (args == null)
F.main(Plugin.GetName(), "You need to include a player's name.");
else
{
CommandCenter.GetClientManager().checkPlayerName(caller, args[0], new Callback<Boolean>()
{
public void run(Boolean result)
{
if (result)
{
Plugin.addFriend(caller, args[0]);
}
}
});
}
}
}

View File

@ -0,0 +1,37 @@
package mineplex.core.friend.command;
import org.bukkit.entity.Player;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.F;
import mineplex.core.friend.FriendManager;
public class DeleteFriend extends CommandBase<FriendManager>
{
public DeleteFriend(FriendManager plugin)
{
super(plugin, Rank.ALL, "unfriend");
}
@Override
public void Execute(final Player caller, final String[] args)
{
if (args == null)
F.main(Plugin.GetName(), "You need to include a player's name.");
else
{
CommandCenter.GetClientManager().checkPlayerName(caller, args[0], new Callback<Boolean>()
{
public void run(Boolean result)
{
if (result)
{
Plugin.removeFriend(caller, args[0]);
}
}
});
}
}
}

View File

@ -0,0 +1,9 @@
package mineplex.core.friend.data;
import java.util.ArrayList;
import java.util.List;
public class FriendData
{
public List<FriendStatus> Friends = new ArrayList<FriendStatus>();
}

View File

@ -0,0 +1,115 @@
package mineplex.core.friend.data;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.database.RepositoryBase;
import mineplex.core.database.ResultSetCallable;
import mineplex.core.database.column.ColumnVarChar;
public class FriendRepository extends RepositoryBase
{
private static String CREATE_FRIEND_TABLE = "CREATE TABLE IF NOT EXISTS accountFriend (id INT NOT NULL AUTO_INCREMENT, uuidSource VARCHAR(100), uuidTarget VARCHAR(100), mutual BOOL, PRIMARY KEY (id), INDEX uuidTargetIndex (uuidTarget));";
private static String RETRIEVE_MULTIPLE_FRIEND_RECORDS = "SELECT uuidSource, tA.Name, mutual FROM accountFriend INNER Join accounts AS fA ON fA.uuid = uuidSource INNER JOIN accounts AS tA ON tA.uuid = uuidTarget LEFT JOIN playerMap ON tA.name = playerName WHERE uuidSource IN ";
private static String RETRIEVE_FRIEND_RECORDS = "SELECT tA.Name, mutual, serverName, tA.lastLogin FROM accountFriend INNER Join accounts AS fA ON fA.uuid = uuidSource INNER JOIN accounts AS tA ON tA.uuid = uuidTarget LEFT JOIN playerMap ON tA.name = playerName WHERE uuidSource = ?;";
private static String ADD_FRIEND_RECORD = "INSERT INTO accountFriend (uuidSource, uuidTarget) SELECT fA.uuid AS uuidSource, tA.uuid AS uuidTarget FROM accounts as fA LEFT JOIN accounts AS tA ON tA.name = ? WHERE fA.uuid = ?;";
private static String DELETE_FRIEND_RECORD = "DELETE aF FROM accountFriend AS aF INNER JOIN accounts ON accounts.name = ? WHERE uuidSource = ? AND uuidTarget = accounts.uuid;";
public FriendRepository(JavaPlugin plugin)
{
super(plugin, "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10", "root", "tAbechAk3wR7tuTh");
}
@Override
protected void initialize()
{
executeUpdate(CREATE_FRIEND_TABLE);
}
@Override
protected void update()
{
}
public boolean addFriend(String uuid, String name)
{
return executeUpdate(ADD_FRIEND_RECORD, new ColumnVarChar("name", 40, name), new ColumnVarChar("uuid", 100, uuid)) > 0;
}
public boolean removeFriend(String uuid, String name)
{
return executeUpdate(DELETE_FRIEND_RECORD, new ColumnVarChar("name", 40, name), new ColumnVarChar("uuid", 100, uuid)) > 0;
}
public NautHashMap<String, FriendData> getFriendsForAll(Player...players)
{
final NautHashMap<String, FriendData> friends = new NautHashMap<String, FriendData>();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(RETRIEVE_MULTIPLE_FRIEND_RECORDS + "(");
for (Player player : players)
{
stringBuilder.append("'" + player.getUniqueId() + "', ");
}
stringBuilder.delete(stringBuilder.length() - 2, stringBuilder.length());
stringBuilder.append(");");
executeQuery(stringBuilder.toString(), new ResultSetCallable()
{
public void processResultSet(ResultSet resultSet) throws SQLException
{
while (resultSet.next())
{
FriendStatus friend = new FriendStatus();
String uuidSource = resultSet.getString(1);
friend.Name = resultSet.getString(2);
friend.Mutual = resultSet.getBoolean(3);
friend.ServerName = resultSet.getString(4);
friend.LastSeenOnline = resultSet.getLong(5);
if (!friends.containsKey(uuidSource))
friends.put(uuidSource, new FriendData());
friends.get(uuidSource).Friends.add(friend);
}
}
});
return friends;
}
public FriendData loadClientInformation(final UUID uniqueId)
{
final FriendData friendData = new FriendData();
executeQuery(RETRIEVE_FRIEND_RECORDS, new ResultSetCallable()
{
public void processResultSet(ResultSet resultSet) throws SQLException
{
while (resultSet.next())
{
FriendStatus friend = new FriendStatus();
friend.Name = resultSet.getString(1);
friend.Mutual = resultSet.getBoolean(2);
friend.ServerName = resultSet.getString(3);
friend.LastSeenOnline = resultSet.getLong(4);
System.out.println("Adding friend " + friend.Name + " for UUID " + uniqueId.toString());
friendData.Friends.add(friend);
}
}
}, new ColumnVarChar("uuidSource", 100, uniqueId.toString()));
return friendData;
}
}

View File

@ -0,0 +1,10 @@
package mineplex.core.friend.data;
public class FriendStatus
{
public String Name;
public String ServerName;
public boolean Online;
public long LastSeenOnline;
public boolean Mutual;
}

View File

@ -0,0 +1,46 @@
package mineplex.core.friend.ui;
import java.util.Collections;
import java.util.List;
import mineplex.core.common.util.UtilTime;
import mineplex.core.common.util.UtilTime.TimeUnit;
import mineplex.core.friend.FriendSorter;
import mineplex.core.friend.data.FriendStatus;
import org.bukkit.ChatColor;
public class FriendTabList extends TabList
{
private static FriendSorter _friendSorter = new FriendSorter();
public FriendTabList(List<FriendStatus> friends)
{
super();
set(0, 0, ChatColor.GOLD + " Name");
set(1, 0, ChatColor.GOLD + " Location");
set(2, 0, ChatColor.GOLD + " Status");
updateFriends(friends);
System.out.println("created friend tablist with " + friends.size() + " friends");
}
public void updateFriends(List<FriendStatus> friends)
{
Collections.sort(friends, _friendSorter);
int row = 1;
for (int i = 0; i < 20 && i < friends.size(); i++)
{
FriendStatus status = friends.get(i);
set(0, row, (status.Mutual ? ChatColor.GREEN : ChatColor.YELLOW) + status.Name);
set(1, row, status.Mutual ? ChatColor.GREEN + status.ServerName : ChatColor.YELLOW + "Unknown");
set(2, row, (status.Mutual ? ChatColor.GREEN : ChatColor.YELLOW) + (status.Online ? "Online" : UtilTime.convert(status.LastSeenOnline, 2, TimeUnit.MINUTES) + ""));
System.out.println("Added friend " + status.Name + " to tablist");
}
}
}

View File

@ -0,0 +1,69 @@
package mineplex.core.friend.ui;
import net.minecraft.server.v1_7_R3.EntityPlayer;
import net.minecraft.server.v1_7_R3.PacketPlayOutPlayerInfo;
public class LineTracker
{
private String _line = null;
private String _oldLine = null;
private PacketPlayOutPlayerInfo _clearOldPacket;
private PacketPlayOutPlayerInfo _addNewPacket;
private PacketPlayOutPlayerInfo _clearNewPacket;
public LineTracker(String line)
{
setLine(line);
}
public boolean setLine(String s)
{
if (s != null && s.length() > 16)
s = s.substring(0, 16);
if (_line != null && _line.compareTo(s) == 0)
return false;
_oldLine = _line;
_line = s;
if (_oldLine != null)
{
_clearOldPacket = new PacketPlayOutPlayerInfo(_oldLine, false, 0);
}
if (_line != null)
{
_addNewPacket = new PacketPlayOutPlayerInfo(_line, true, 0);
_clearNewPacket = new PacketPlayOutPlayerInfo(_line, false, 0);
}
return true;
}
public void displayLineToPlayer(EntityPlayer entityPlayer)
{
if (_oldLine != null)
{
entityPlayer.playerConnection.sendPacket(_clearOldPacket);
}
if (_line != null)
{
entityPlayer.playerConnection.sendPacket(_addNewPacket);
}
}
public void removeLineForPlayer(EntityPlayer entityPlayer)
{
if (_line != null)
{
entityPlayer.playerConnection.sendPacket(_clearNewPacket);
}
}
public void clearOldLine()
{
_oldLine = null;
}
}

View File

@ -0,0 +1,113 @@
package mineplex.core.friend.ui;
import java.util.HashSet;
import net.minecraft.server.v1_7_R3.EntityPlayer;
import org.bukkit.ChatColor;
import org.bukkit.craftbukkit.v1_7_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import mineplex.core.common.util.NautHashMap;
public class TabList implements Listener
{
private static NautHashMap<Integer, String> _invisibleHolders = new NautHashMap<Integer, String>();
private NautHashMap<Integer, LineTracker> _tabSlots = new NautHashMap<Integer, LineTracker>();
private HashSet<Integer> _updatedSlots = new HashSet<Integer>();
private boolean _update;
static {
String spaces = "";
for (int i=0; i < 60; i++)
{
int markerSymbol = i / 15;
String symbol = null;
if (i % 15 == 0)
spaces = "";
else
spaces += " ";
if (markerSymbol == 0)
{
symbol = ChatColor.GREEN + "";
}
else if (markerSymbol == 1)
{
symbol = ChatColor.RED + "";
}
else if (markerSymbol == 2)
{
symbol = ChatColor.BLUE + "";
}
else if (markerSymbol == 3)
{
symbol = ChatColor.BLACK + "";
}
_invisibleHolders.put(i, symbol + spaces);
}
}
public TabList()
{
for (Integer i=0; i < 60; i++)
{
_tabSlots.put(i, new LineTracker(_invisibleHolders.get(i)));
}
}
public void set(int column, int row, String lineContent)
{
int index = row * 3 + column;
if (index >= 60)
return;
if (lineContent == null || lineContent.isEmpty())
lineContent = _invisibleHolders.get(index);
if (_tabSlots.get(index).setLine(lineContent))
{
_updatedSlots.add(index);
_update = true;
}
}
public void refreshForPlayer(Player player)
{
EntityPlayer entityPlayer = ((CraftPlayer)player).getHandle();
int indexChanged = 60;
for (int i=0; i < 60; i++)
{
if (indexChanged == 60 && _updatedSlots.contains(i))
{
indexChanged = i;
}
else if (indexChanged != 60 && !_updatedSlots.contains(i))
{
_tabSlots.get(i).removeLineForPlayer(entityPlayer);
}
}
for (int i=indexChanged; i < 60; i++)
{
_tabSlots.get(i).displayLineToPlayer(entityPlayer);
}
_update = false;
_updatedSlots.clear();
}
public boolean shouldUpdate()
{
return _update;
}
}

View File

@ -3,16 +3,19 @@ package mineplex.core.logger;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
public class Logger
{
public static Logger Instance;
private static JavaPlugin _plugin;
private LoggerRepository _repository;
public static void initialize(JavaPlugin plugin)
{
_plugin = plugin;
Instance = new Logger(plugin);
}
@ -47,14 +50,20 @@ public class Logger
}
}
public void log(String message)
public void log(final String message)
{
_repository.saveLog(message);
Bukkit.getServer().getScheduler().runTaskAsynchronously(_plugin, new Runnable()
{
public void run()
{
_repository.saveLog(message);
}
});
}
public void log(Throwable exception)
{
List<String> messages = new ArrayList<String>();
final List<String> messages = new ArrayList<String>();
messages.add("[Exception Start]" + exception.getMessage());
@ -65,6 +74,12 @@ public class Logger
messages.add("[Exception End]");
_repository.saveLog(messages.toArray(new String[0]));
Bukkit.getServer().getScheduler().runTaskAsynchronously(_plugin, new Runnable()
{
public void run()
{
_repository.saveLog(messages.toArray(new String[0]));
}
});
}
}

View File

@ -1,22 +0,0 @@
package mineplex.core.mysql;
import org.bukkit.plugin.java.JavaPlugin;
public class AccountPreferenceRepository extends RepositoryBase
{
private static String CREATE_ACCOUNT_PREFERENCE_TABLE = "CREATE TABLE IF NOT EXISTS AccountPreferences (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (id));";
public AccountPreferenceRepository(JavaPlugin plugin)
{
super(plugin);
}
@Override
protected void initialize()
{
executeQuery(CREATE_ACCOUNT_PREFERENCE_TABLE);
}
@Override
protected void update() { }
}

View File

@ -1,114 +0,0 @@
package mineplex.core.mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.bukkit.plugin.java.JavaPlugin;
public abstract class RepositoryBase
{
private String _connectionString;
private String _userName;
private String _password;
public RepositoryBase(JavaPlugin plugin)
{
_connectionString = plugin.getConfig().getString("serverstatus.connectionurl");
_userName = plugin.getConfig().getString("serverstatus.username");
_password = plugin.getConfig().getString("serverstatus.password");
initialize();
update();
}
protected abstract void initialize();
protected abstract void update();
protected Connection getConnection() throws SQLException
{
return DriverManager.getConnection(_connectionString, _userName, _password);
}
protected int executeQuery(String query)
{
Connection connection = null;
PreparedStatement preparedStatement = null;
int affectedRows = 0;
try
{
connection = DriverManager.getConnection(_connectionString, _userName, _password);
preparedStatement = connection.prepareStatement(query);
affectedRows = preparedStatement.executeUpdate();
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (connection != null)
{
try
{
connection.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
return affectedRows;
}
protected int executeStatement(PreparedStatement preparedStatement)
{
Connection connection = null;
int affectedRows = 0;
try
{
connection = DriverManager.getConnection(_connectionString, _userName, _password);
affectedRows = preparedStatement.executeUpdate();
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (connection != null)
{
try
{
connection.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
return affectedRows;
}
}

View File

@ -0,0 +1,46 @@
package mineplex.core.playerTracker;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniPlugin;
import mineplex.core.account.event.ClientUnloadEvent;
public class PlayerTracker extends MiniPlugin
{
private PlayerTrackerRepository _repository = null;
public PlayerTracker(JavaPlugin plugin, String serverName, boolean us)
{
super("Player Tracker", plugin);
_repository = new PlayerTrackerRepository();
_repository.initialize(serverName, us);
}
@EventHandler
public void trackPlayer(final PlayerJoinEvent event)
{
Bukkit.getServer().getScheduler().runTaskAsynchronously(GetPlugin(), new Runnable()
{
public void run()
{
_repository.updatePlayerServer(event.getPlayer().getName());
}
});
}
@EventHandler
public void untrackPlayer(final ClientUnloadEvent event)
{
Bukkit.getServer().getScheduler().runTaskAsynchronously(GetPlugin(), new Runnable()
{
public void run()
{
_repository.deleteServerTransfers(event.GetName());
}
});
}
}

View File

@ -0,0 +1,206 @@
package mineplex.core.playerTracker;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PlayerTrackerRepository
{
private static Object _connectionLock = new Object();
private String _connectionString = "jdbc:mysql://db.mineplex.com:3306/Account?autoReconnect=true&failOverReadOnly=false&maxReconnects=10";
private String _userName = "root";
private String _password = "tAbechAk3wR7tuTh";
private String _serverName = "";
private boolean _us = true;
private static String CREATE_PLAYERMAP_TABLE = "CREATE TABLE IF NOT EXISTS playerMap (id INT NOT NULL AUTO_INCREMENT, playerName VARCHAR(256), serverName VARCHAR(256), us BOOLEAN NOT NULL DEFAULT 1, PRIMARY KEY (id), UNIQUE INDEX playerIndex (playerName));";
private static String RETRIEVE_PLAYERMAP = "SELECT playerName, serverName FROM playerMap WHERE playerName = ? AND us = ?;";
private static String INSERT_PLAYERMAP = "INSERT INTO playerMap (playerName, serverName, us) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE serverName = VALUES(serverName), us = VALUES(us);";
private static String DELETE_PLAYERMAP = "DELETE FROM playerMap WHERE playerName = ? AND serverName = ? AND us = ?;";
private Connection _connection = null;
public void initialize(String serverName, boolean us)
{
_serverName = serverName;
_us = us;
PreparedStatement preparedStatement = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
// Create table
preparedStatement = _connection.prepareStatement(CREATE_PLAYERMAP_TABLE);
preparedStatement.execute();
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
public String retrievePlayerServer(String playerName)
{
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
String server = "N/A";
try
{
synchronized (_connectionLock)
{
if (_connection.isClosed())
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
preparedStatement = _connection.prepareStatement(RETRIEVE_PLAYERMAP);
preparedStatement.setString(1, playerName);
preparedStatement.setBoolean(2, _us);
resultSet = preparedStatement.executeQuery();
while (resultSet.next())
{
server = resultSet.getString(1);
}
}
}
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 server;
}
public void deleteServerTransfers(String playerName)
{
PreparedStatement preparedStatement = null;
try
{
synchronized (_connectionLock)
{
if (_connection.isClosed())
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
preparedStatement = _connection.prepareStatement(DELETE_PLAYERMAP);
preparedStatement.setString(1, playerName);
preparedStatement.setString(2, _serverName);
preparedStatement.setBoolean(3, _us);
preparedStatement.executeUpdate();
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
public void updatePlayerServer(String playerName)
{
PreparedStatement preparedStatement = null;
try
{
synchronized (_connectionLock)
{
if (_connection.isClosed())
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
preparedStatement = _connection.prepareStatement(INSERT_PLAYERMAP);
preparedStatement.setString(1, playerName);
preparedStatement.setString(2, _serverName);
preparedStatement.setBoolean(3, _us);
preparedStatement.executeUpdate();
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
}

View File

@ -0,0 +1,68 @@
package mineplex.core.portal.Commands;
import org.bukkit.entity.Player;
import mineplex.core.command.*;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.portal.Portal;
public class SendCommand extends CommandBase<Portal>
{
public SendCommand(Portal plugin)
{
super(plugin, Rank.ADMIN, "send");
}
@Override
public void Execute(final Player player, final String[] args)
{
if(args == null || args.length == 0)
{
UtilPlayer.message(player, F.main(Plugin.GetName(), C.cRed + "Your arguments are inappropriate for this command!"));
return;
}
else if(args.length == 2)
{
final String playerTarget = args[0];
final String serverTarget = args[1];
CommandCenter.GetClientManager().checkPlayerName(player, playerTarget, new Callback<Boolean>()
{
public void run(Boolean playerExists)
{
if (!playerExists)
{
UtilPlayer.message(player, F.main(Plugin.GetName(), C.cGray + "Player " + C.cGold + playerTarget + C.cGray + " does not exist!"));
return;
}
Plugin.DoesServerExist(serverTarget, new Callback<Boolean>()
{
public void run(Boolean serverExists)
{
if (!serverExists)
{
UtilPlayer.message(player, F.main(Plugin.GetName(), C.cGray + "Server " + C.cGold + serverTarget + C.cGray + " does not exist!"));
return;
}
Plugin.AddTransferRecord(playerTarget, serverTarget);
UtilPlayer.message(player, F.main(Plugin.GetName(), C.cGray + "You have sent player: " + C.cGold + playerTarget + C.cGray + " to server: " + C.cGold + serverTarget + C.cGray + "!"));
return;
}
});
}
});
}
else
{
UtilPlayer.message(player, F.main(Plugin.GetName(), C.cRed + "Your arguments are inappropriate for this command!"));
return;
}
}
}

View File

@ -0,0 +1,109 @@
package mineplex.core.portal.Commands;
import org.bukkit.entity.Player;
import mineplex.core.command.*;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.portal.Portal;
public class ServerCommand extends CommandBase<Portal>
{
public ServerCommand(Portal plugin)
{
super(plugin, Rank.ALL, "server");
}
@Override
public void Execute(final Player player, final String[] args)
{
final Rank playerRank = CommandCenter.GetClientManager().Get(player).GetRank();
final String serverName = Plugin.GetPlugin().getConfig().getString("serverstatus.name");
if (args == null || args.length == 0)
{
UtilPlayer.message(player,
F.main(Plugin.GetName(), C.cGray + "You are currently on server: " + C.cGold + serverName));
return;
}
else if (args.length == 1)
{
if (serverName.equalsIgnoreCase(args[0]))
{
UtilPlayer.message(
player,
F.main(Plugin.GetName(), "You are already on " + C.cGold + serverName + C.cGray
+ "!"));
}
else
{
Plugin.DoesServerExist(args[0], new Callback<Boolean>()
{
public void run(final Boolean serverExists)
{
if (!serverExists)
{
UtilPlayer.message(
player,
F.main(Plugin.GetName(), "Server " + C.cGold + args[0]
+ C.cGray + " does not exist!"));
return;
}
boolean deniedAccess = false;
String servUp = args[0].toUpperCase();
if (servUp.contains("HERO"))
{
if (playerRank.Has(Rank.HERO))
Plugin.SendPlayerToServerWithMessage(player, args[0]);
else
deniedAccess = true;
}
else if (servUp.contains("ULTRA") || servUp.contains("BETA"))
{
if (playerRank.Has(Rank.ULTRA))
Plugin.SendPlayerToServerWithMessage(player, args[0]);
else
deniedAccess = true;
}
else if (servUp.contains("STAFF"))
{
if (playerRank.Has(Rank.HELPER))
Plugin.SendPlayerToServerWithMessage(player, args[0]);
else
deniedAccess = true;
}
else if (servUp.contains("TEST"))
{
if (playerRank.Has(Rank.MODERATOR))
Plugin.SendPlayerToServerWithMessage(player, args[0]);
else
deniedAccess = true;
}
else
{
Plugin.SendPlayerToServerWithMessage(player, args[0]);
}
if (deniedAccess)
{
UtilPlayer.message(
player,
F.main(Plugin.GetName(), C.cRed + "You don't have permission to join " + C.cGold + args[0]));
}
}
});
}
}
else
{
UtilPlayer.message(player,
F.main(Plugin.GetName(), C.cRed + "Your arguments are inappropriate for this command!"));
return;
}
}
}

View File

@ -3,39 +3,44 @@ package mineplex.core.portal;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Iterator;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniPlugin;
import mineplex.core.common.util.C;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.F;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.portal.Commands.*;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
public class Portal extends MiniPlugin
{
private static Object _transferLock = new Object();
private HashSet<String> _connectingPlayers = new HashSet<String>();
private PortalRepository _repository= new PortalRepository();
private PortalRepository _repository = new PortalRepository();
private List<String> _transfers = new ArrayList<String>();
private boolean _retrieve = true;
public Portal(JavaPlugin plugin)
private String _serverName;
public Portal(JavaPlugin plugin, String serverName)
{
super("Portal", plugin);
_serverName = serverName;
Bukkit.getMessenger().registerOutgoingPluginChannel(GetPlugin(), "BungeeCord");
_repository.initialize(plugin.getConfig().getBoolean("serverstatus.us"));
_repository.initialize(plugin.getConfig().getBoolean("serverstatus.us"), plugin.getConfig().getString("serverstatus.connectionurl"));
}
public void SendAllPlayers(String serverName)
@ -46,6 +51,19 @@ public class Portal extends MiniPlugin
}
}
public void SendPlayerToServerWithMessage(Player player, String serverName)
{
SendPlayerToServer(player, serverName);
player.playSound(player.getLocation(), Sound.PORTAL, 0.5f, 2f);
UtilPlayer
.message(
player,
F.main(GetName(), C.cGray + "You have been sent to server: " + C.cGold + serverName
+ C.cGray + "!"));
}
public void SendPlayerToServer(final Player player, String serverName)
{
if (_connectingPlayers.contains(player.getName()))
@ -87,36 +105,52 @@ public class Portal extends MiniPlugin
}, 20L);
}
@EventHandler
public void addTransferDelete(final PlayerQuitEvent event)
{
boolean delete = false;
synchronized (_transferLock)
public void AddTransferRecord(final String playerName, final String serverName)
{
Bukkit.getScheduler().runTaskAsynchronously(GetPlugin(), new Runnable()
{
delete = _transfers.remove(event.getPlayer().getName());
}
if (delete)
{
Bukkit.getScheduler().runTaskAsynchronously(GetPlugin(), new Runnable()
public void run()
{
public void run()
_repository.addServerTransfer(playerName, serverName);
}
});
}
public void DoesServerExist(final String serverName, final Callback<Boolean> callback)
{
if (callback == null)
return;
Bukkit.getScheduler().runTaskAsynchronously(GetPlugin(), new Runnable()
{
public void run()
{
final boolean serverExists = _repository.doesServerExist(serverName);
Bukkit.getScheduler().runTask(GetPlugin(), new Runnable()
{
_repository.deleteServerTransfers(event.getPlayer().getName());
}
});
}
public void run()
{
callback.run(serverExists);
}
});
}
});
}
public void AddCommands()
{
AddCommand(new ServerCommand(this));
AddCommand(new SendCommand(this));
}
@EventHandler
public void checkForServerTransfers(UpdateEvent event)
{
_retrieve = !_retrieve;
if (event.getType() != UpdateType.SEC || Bukkit.getOnlinePlayers().length == 0)
return;
_retrieve = !_retrieve;
if (_retrieve)
{
@ -124,12 +158,19 @@ public class Portal extends MiniPlugin
{
public void run()
{
final NautHashMap<String, String> entries = _repository.retrieveServerTransfers();
final NautHashMap<String, String> entries = _repository.retrieveServerTransfers();
synchronized (_transferLock)
for (Iterator<String> iterator = entries.keySet().iterator(); iterator.hasNext();)
{
_transfers.addAll(entries.keySet());
}
String playerName = iterator.next();
String serverName = entries.get(playerName);
if (serverName.equalsIgnoreCase(_serverName))
{
_repository.deleteServerTransfers(playerName);
iterator.remove();
}
}
Bukkit.getScheduler().runTask(GetPlugin(), new Runnable()
{

View File

@ -5,12 +5,18 @@ import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.status.ServerStatusData;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.mysql.jdbc.exceptions.jdbc4.CommunicationsException;
public class PortalRepository
{
private static Object _connectionLock = new Object();
@ -18,18 +24,23 @@ public class PortalRepository
private String _connectionString = "jdbc:mysql://db.mineplex.com:3306/Queue?autoReconnect=true&failOverReadOnly=false&maxReconnects=10";
private String _userName = "root";
private String _password = "tAbechAk3wR7tuTh";
private String _altConnectString = "";
private boolean _us = true;
private static String CREATE_TRANSFER_TABLE = "CREATE TABLE IF NOT EXISTS playerServerTransfer (id INT NOT NULL AUTO_INCREMENT, playerName VARCHAR(256), serverName VARCHAR(256), PRIMARY KEY (id));";
private static String RETRIEVE_TRANSFER_RECORDS = "SELECT playerName, serverName FROM playerServerTransfer WHERE playerName IN ";
private static String DELETE_TRANSFER_RECORDS = "DELETE FROM playerServerTransfer WHERE playerName = ?;";
private static String ADD_TRANSFER_RECORD = "INSERT INTO playerServerTransfer (playerName,serverName) VALUES(?,?);";
private static String RETRIEVE_SERVER_STATUSES = "SELECT ServerStatus.serverName, motd, players, maxPlayers, now(), updated FROM ServerStatus INNER JOIN DynamicServers ON ServerStatus.address = DynamicServers.privateAddress WHERE DynamicServers.US = ? AND ServerStatus.serverName = ?;";
private Connection _connection = null;
private Connection _altConnection = null;
public void initialize(boolean us)
public void initialize(boolean us, String altConnectString)
{
_us = us;
_altConnectString = altConnectString;
PreparedStatement preparedStatement = null;
@ -172,4 +183,117 @@ public class PortalRepository
}
}
}
public void addServerTransfer(String playerName, String serverName)
{
PreparedStatement preparedStatement = null;
try
{
synchronized (_connectionLock)
{
if (_connection.isClosed())
{
_connection = DriverManager.getConnection(_connectionString, _userName, _password);
}
preparedStatement = _connection.prepareStatement(ADD_TRANSFER_RECORD);
preparedStatement.setString(1, playerName);
preparedStatement.setString(2, serverName);
preparedStatement.executeUpdate();
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
if (preparedStatement != null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
public boolean doesServerExist(String serverName)
{
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
List<ServerStatusData> serverData = new ArrayList<ServerStatusData>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try
{
if (_altConnection == null || _altConnection.isClosed())
{
_altConnection = DriverManager.getConnection(_altConnectString, _userName, _password);
}
preparedStatement = _altConnection.prepareStatement(RETRIEVE_SERVER_STATUSES);
preparedStatement.setBoolean(1, _us);
preparedStatement.setString(2, serverName);
resultSet = preparedStatement.executeQuery();
while (resultSet.next())
{
ServerStatusData serverStatusData = new ServerStatusData();
serverStatusData.Name = resultSet.getString(1);
serverStatusData.Motd = resultSet.getString(2);
serverStatusData.Players = resultSet.getInt(3);
serverStatusData.MaxPlayers = resultSet.getInt(4);
long current = dateFormat.parse(resultSet.getString(5)).getTime();
long updated = dateFormat.parse(resultSet.getString(6)).getTime();
if (current - updated < 15000)
serverData.add(serverStatusData);
}
}
catch (CommunicationsException exception)
{
return doesServerExist(serverName);
}
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 !serverData.isEmpty();
}
}

View File

@ -58,49 +58,6 @@ public class Punish extends MiniPlugin
@EventHandler
public void OnClientWebResponse(ClientWebResponseEvent event)
{
/*
JsonReader reader = null;
try
{
while (reader.hasNext())
{
if (reader.nextName().equalsIgnoreCase("Punish"))
{
reader.beginObject();
// TODO Parse infractions/punishments here
// PunishClient client = new PunishClient();
// client.AddInfraction(token.Category, new Infraction(token.Reason, token.Admin, token.Time));
// client.AddPunishment(token.Category, new Punishment(token.PunishmentSentence, token.Reason, token.Admin, token.Hours, token.Time));
// _punishClients.put(event.GetClient().GetPlayerName(), client);
break;
}
reader.endObject();
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
*/
PunishClientToken token = new Gson().fromJson(event.GetResponse(), PunishClientToken.class);
LoadClient(token);
}
@ -121,7 +78,7 @@ public class Punish extends MiniPlugin
if (client.IsBanned())
{
Punishment punishment = client.GetPunishment(PunishmentSentence.Ban);
String time = F.time(UtilTime.convertString((long)(punishment.GetHours() * 3600000), 0, TimeUnit.FIT));
String time = F.time(UtilTime.convertString(punishment.GetRemaining(), 0, TimeUnit.FIT));
if (punishment.GetHours() == -1)
time = C.cRed + "Permanent";
@ -234,16 +191,18 @@ public class Punish extends MiniPlugin
}
}
}
}, playerName, category.toString(), sentence, reason, duration, caller == null ? "Mineplex Anti-Cheat" : caller.getName(), severity, System.currentTimeMillis());
}, playerName, category.toString(), sentence, reason, duration, caller == null ? "Mineplex Anti-Cheat" : caller.getName(), severity);
}
public void LoadClient(PunishClientToken token)
{
PunishClient client = new PunishClient();
long timeDifference = System.currentTimeMillis() - token.Time;
for (PunishmentToken punishment : token.Punishments)
{
client.AddPunishment(Category.valueOf(punishment.Category), new Punishment(punishment.PunishmentId, PunishmentSentence.valueOf(punishment.Sentence), Category.valueOf(punishment.Category), punishment.Reason, punishment.Admin, punishment.Duration, punishment.Severity, punishment.Time, punishment.Active, punishment.Removed, punishment.RemoveAdmin, punishment.RemoveReason));
client.AddPunishment(Category.valueOf(punishment.Category), new Punishment(punishment.PunishmentId, PunishmentSentence.valueOf(punishment.Sentence), Category.valueOf(punishment.Category), punishment.Reason, punishment.Admin, punishment.Duration, punishment.Severity, punishment.Time + timeDifference, punishment.Active, punishment.Removed, punishment.RemoveAdmin, punishment.RemoveReason));
}
_punishClients.put(token.Name.toLowerCase(), client);

View File

@ -20,7 +20,7 @@ public class PunishRepository
_webAddress = webServerAddress;
}
public void Punish(Callback<String> callback, String target, String category, PunishmentSentence punishment, String reason, double duration, String admin, int severity, long time)
public void Punish(Callback<String> callback, String target, String category, PunishmentSentence punishment, String reason, double duration, String admin, int severity)
{
PunishToken token = new PunishToken();
token.Target = target;
@ -29,7 +29,6 @@ public class PunishRepository
token.Reason = reason;
token.Duration = duration;
token.Admin = admin;
token.Time = time;
token.Severity = severity;
new AsyncJsonWebCall(_webAddress + "PlayerAccount/Punish").Execute(String.class, callback, token);

View File

@ -5,5 +5,6 @@ import java.util.List;
public class PunishClientToken
{
public String Name;
public long Time;
public List<PunishmentToken> Punishments;
}

View File

@ -1,8 +0,0 @@
package mineplex.core.server;
import mineplex.core.common.util.Callback;
public interface IPurchaseRepository
{
void PurchaseSalesPackage(Callback<String> callback, String name, boolean usingCredits, int salesPackageId);
}

View File

@ -1,7 +0,0 @@
package mineplex.core.server;
public class Server
{
public String Address;
public int Port;
}

View File

@ -1,212 +0,0 @@
package mineplex.core.server;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken;
import mineplex.core.server.packet.Packet;
import mineplex.core.server.remotecall.JsonWebCall;
public class ServerBroadcaster extends Thread
{
private static Object _queueLock = new Object();
private static Object _serverMapLock = new Object();
private HashSet<String> _serverMap = new HashSet<String>();
private List<Packet> _queue = new ArrayList<Packet>();
private String _webAddress;
private boolean _running = true;
private boolean _retrievingServers = false;
private long _updateInterval = 15000;
private long _lastUpdate;
private boolean _debug = false;
public ServerBroadcaster(String webAddress)
{
_webAddress = webAddress;
}
public void QueuePacket(Packet packet)
{
synchronized(_queueLock)
{
_queue.add(packet);
}
}
@Override
public void run()
{
while (_running)
{
if (!HasPackets() || !HasServers())
{
try
{
Thread.sleep(25);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
if (System.currentTimeMillis() - _lastUpdate > _updateInterval)
{
RetrieveActiveServers();
}
continue;
}
Packet packet = null;
synchronized(_queueLock)
{
packet = _queue.remove(0);
}
synchronized(_serverMapLock)
{
for (String server : _serverMap)
{
Socket socket = null;
DataOutputStream dataOutput = null;
try
{
socket = new Socket(server.split(":")[0], Integer.parseInt(server.split(":")[1]));
dataOutput = new DataOutputStream(socket.getOutputStream());
packet.Write(dataOutput);
dataOutput.flush();
if (_debug)
System.out.println("Sent packet to : " + socket.getInetAddress().getHostAddress() + ":" + socket.getPort());
}
catch (Exception ex)
{
System.out.println("ServerTalker.run Exception(" + server + ") : " + ex.getMessage());
}
finally
{
try
{
if (dataOutput != null)
dataOutput.close();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
if (socket != null)
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
}
public boolean HasPackets()
{
synchronized(_queueLock)
{
return _queue.size() != 0;
}
}
public boolean HasServers()
{
synchronized(_serverMapLock)
{
return _serverMap.size() != 0;
}
}
public void PrintPackets()
{
System.out.println("Listing Packets:");
synchronized(_queueLock)
{
if (_queue.isEmpty())
{
System.out.println("Packet queue empty!");
}
else
{
for (Packet packet : _queue)
{
System.out.println(packet.getClass());
}
}
}
}
public void PrintServers()
{
System.out.println("Listing Servers:");
if (_retrievingServers)
{
System.out.println("Retrieving servers. Please check again in a few seconds.");
}
synchronized(_serverMapLock)
{
if (_serverMap.isEmpty())
{
System.out.println("Server list empty!");
}
else
{
for (String server : _serverMap)
{
System.out.println(server);
}
}
}
}
private void RetrieveActiveServers()
{
if (_debug)
System.out.println("Updating servers...");
List<String> servers = new JsonWebCall(_webAddress + "Servers/GetServers").Execute(new TypeToken<List<String>>(){}.getType(), null);
synchronized(_serverMapLock)
{
_serverMap.clear();
if (servers.size() > 0)
{
for (String server : servers)
{
_serverMap.add(server);
}
}
else
{
System.out.println("No servers registered at '" + _webAddress + "'!");
}
}
_lastUpdate = System.currentTimeMillis();
}
}

View File

@ -1,146 +0,0 @@
package mineplex.core.server;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import mineplex.core.server.packet.IPacketHandler;
import mineplex.core.server.packet.PacketType;
import mineplex.core.server.remotecall.JsonWebCall;
import org.bukkit.Bukkit;
import org.bukkit.plugin.PluginManager;
public class ServerListener extends Thread
{
private IPacketHandler _packetHandler;
private final String _host;
private final int _port;
private String _webServer;
private ServerSocket server;
private boolean running = true;
public ServerListener(IPacketHandler packetHandler, String webserver, String host, int port)
{
_packetHandler = packetHandler;
_webServer = webserver;
_host = host;
_port = port;
Initialize();
System.out.println("Initialized ServerListener");
new JsonWebCall(_webServer + "Servers/RegisterServer").Execute(host + ":" + port);
System.out.println("Finished with constructor");
}
public ServerListener(String webserver, String host, int port)
{
this(null, webserver, host, port);
}
private void Initialize()
{
try
{
server = new ServerSocket();
server.bind(new InetSocketAddress(_host, _port));
System.out.println("Listening to " + _host + ":" + _port);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public void Shutdown()
{
running = false;
if (server == null)
return;
try
{
server.close();
}
catch (Exception ex)
{
System.out.println("ServerListener.Shutdown Exception : " + ex.getMessage());
}
new JsonWebCall(_webServer + "Servers/RemoveServer").Execute(_host + ":" + _port);
}
@Override
public void run()
{
while (running)
{
Socket socket = null;
DataInputStream dataInput = null;
try
{
socket = server.accept();
socket.setSoTimeout(5000);
dataInput = new DataInputStream(socket.getInputStream());
if (_packetHandler != null)
{
_packetHandler.HandlePacketEvent(PacketType.GetPacketEventById(dataInput.readShort(), dataInput), socket);
}
else
{
PluginManager pluginManager = Bukkit.getPluginManager();
if (pluginManager != null)
Bukkit.getPluginManager().callEvent(PacketType.GetPacketEventById(dataInput.readShort(), dataInput));
}
System.out.println("received packet");
}
catch (Exception ex)
{
System.out.println("ServerListener.run Exception : " + ex.getMessage());
try
{
throw ex;
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
finally
{
try
{
if (dataInput != null)
dataInput.close();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
if (socket != null)
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}

View File

@ -1,141 +0,0 @@
package mineplex.core.server;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import mineplex.core.server.packet.Packet;
public class ServerTalker extends Thread
{
private static Object _queueLock = new Object();
private List<Packet> _queue = new ArrayList<Packet>();
private String _serverAddress;
private boolean _running = true;
private boolean _debug = false;
public ServerTalker(String serverAddress)
{
_serverAddress = serverAddress;
}
public void QueuePacket(Packet packet)
{
synchronized(_queueLock)
{
_queue.add(packet);
}
}
@Override
public void run()
{
while (_running)
{
if (!HasPackets())
{
try
{
Thread.sleep(25);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
continue;
}
Packet packet = null;
synchronized(_queueLock)
{
packet = _queue.remove(0);
}
Socket socket = null;
DataOutputStream dataOutput = null;
try
{
socket = new Socket(_serverAddress.split(":")[0], Integer.parseInt(_serverAddress.split(":")[1]));
dataOutput = new DataOutputStream(socket.getOutputStream());
packet.Write(dataOutput);
dataOutput.flush();
if (_debug)
System.out.println("Sent packet to : " + socket.getInetAddress().getHostAddress() + ":" + socket.getPort());
}
catch (Exception ex)
{
System.out.println("ServerTalker.run Exception(" + _serverAddress + ") : " + ex.getMessage());
_queue.add(packet);
try
{
Thread.sleep(15000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
finally
{
try
{
if (dataOutput != null)
dataOutput.close();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
if (socket != null)
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
public boolean HasPackets()
{
synchronized(_queueLock)
{
return _queue.size() != 0;
}
}
public void PrintPackets()
{
System.out.println("Listing Packets:");
synchronized(_queueLock)
{
if (_queue.isEmpty())
{
System.out.println("Packet queue empty!");
}
else
{
for (Packet packet : _queue)
{
System.out.println(packet.getClass());
}
}
}
}
}

View File

@ -1,32 +0,0 @@
package mineplex.core.server.event;
import java.util.List;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class GameReadyEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private List<String> _players;
public GameReadyEvent(List<String> players)
{
_players = players;
}
public List<String> GetPlayers()
{
return _players;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

View File

@ -1,30 +0,0 @@
package mineplex.core.server.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class PlayerGameAssignmentEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private String _playerName;
public PlayerGameAssignmentEvent(String playerName)
{
_playerName = playerName;
}
public String GetPlayerName()
{
return _playerName;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

View File

@ -1,30 +0,0 @@
package mineplex.core.server.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class PlayerGameRequestEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private String _playerName;
public PlayerGameRequestEvent(String playerName)
{
_playerName = playerName;
}
public String GetPlayerName()
{
return _playerName;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

View File

@ -1,37 +0,0 @@
package mineplex.core.server.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class PlayerServerAssignmentEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private String _playerName;
private String _serverName;
public PlayerServerAssignmentEvent(String playerName, String serverName)
{
_playerName = playerName;
_serverName = serverName;
}
public String GetPlayerName()
{
return _playerName;
}
public String GetServerName()
{
return _serverName;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

View File

@ -1,37 +0,0 @@
package mineplex.core.server.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class PlayerVoteEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private String _playerName;
private int _pointsReceived;
public PlayerVoteEvent(String playerName, int pointsReceived)
{
_playerName = playerName;
_pointsReceived = pointsReceived;
}
public String GetPlayerName()
{
return _playerName;
}
public int GetPointsReceived()
{
return _pointsReceived;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

View File

@ -1,30 +0,0 @@
package mineplex.core.server.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class ServerReadyEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private String _serverPath;
public ServerReadyEvent(String serverName)
{
_serverPath = serverName;
}
public String GetServerPath()
{
return _serverPath;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

View File

@ -1,57 +0,0 @@
package mineplex.core.server.packet;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import mineplex.core.server.event.GameReadyEvent;
import org.bukkit.event.Event;
public class GameReadyPacket extends Packet
{
private List<String> _players;
public GameReadyPacket() { }
public GameReadyPacket(List<String> players)
{
_players = players;
}
public void ParseStream(DataInputStream dataInput) throws IOException
{
int playerCount = dataInput.readShort();
if (_players == null)
_players = new ArrayList<String>();
for (int i = 0; i < playerCount; i++)
{
_players.add(readString(dataInput, 16));
}
}
public void Write(DataOutputStream dataOutput) throws IOException
{
dataOutput.writeShort(73);
dataOutput.writeShort(_players.size());
for (int i = 0; i < _players.size(); i++)
{
writeString(_players.get(i), dataOutput);
}
}
public Event GetEvent()
{
return new GameReadyEvent(_players);
}
public List<String> GetPlayers()
{
return _players;
}
}

View File

@ -1,10 +0,0 @@
package mineplex.core.server.packet;
import java.net.Socket;
import org.bukkit.event.Event;
public interface IPacketHandler
{
void HandlePacketEvent(Event packetEvent, Socket socket);
}

View File

@ -1,47 +0,0 @@
package mineplex.core.server.packet;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.bukkit.event.Event;
public abstract class Packet
{
public abstract void ParseStream(DataInputStream inputStream) throws IOException;
public abstract void Write(DataOutputStream dataOutput) throws IOException;
public abstract Event GetEvent();
protected String readString(DataInputStream dataInputStream, int maxLength) throws IOException
{
short length = dataInputStream.readShort();
if (length > maxLength)
{
throw new IOException("Received string length longer than maximum allowed (" + length + " > " + maxLength + ")");
}
else if (length < 0)
{
throw new IOException("Received string length is less than zero! Weird string!");
}
else
{
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < length; i++)
{
stringBuilder.append(dataInputStream.readChar());
}
return stringBuilder.toString();
}
}
protected void writeString(String string, DataOutputStream dataOutputStream) throws IOException
{
dataOutputStream.writeShort(string.length());
dataOutputStream.writeChars(string);
}
}

View File

@ -1,68 +0,0 @@
package mineplex.core.server.packet;
import java.io.DataInputStream;
import mineplex.core.common.util.NautHashMap;
import org.bukkit.event.Event;
public enum PacketType
{
ServerReady((short)61, ServerReadyPacket.class),
PlayerGameRequest((short)71, PlayerGameRequestPacket.class),
PlayerServerAssignment((short)72, PlayerServerAssignmentPacket.class),
GameReady((short)73, GameReadyPacket.class),
PlayerVote((short)81, PlayerVotePacket.class);
private short _packetId;
private Class<? extends Packet> _packetClass;
private static NautHashMap<Short, PacketType> _typeMapping;
private PacketType(short id, Class<? extends Packet> packetClass)
{
_packetId = id;
_packetClass = packetClass;
}
public short GetPacketId()
{
return _packetId;
}
public Class<? extends Packet> GetPacketClass()
{
return _packetClass;
}
public static Event GetPacketEventById(short id, DataInputStream dataInputStream) throws Exception
{
if (_typeMapping == null)
{
InitializeMapping();
}
if (!_typeMapping.containsKey(id))
{
throw new Exception("Invalid packet id");
}
Class<? extends Packet> packetClass = _typeMapping.get(id).GetPacketClass();
Packet newPacket = (Packet) packetClass.newInstance();
newPacket.ParseStream(dataInputStream);
return newPacket.GetEvent();
}
private static void InitializeMapping()
{
_typeMapping = new NautHashMap<Short, PacketType>();
for (PacketType packetType : values())
{
_typeMapping.put(packetType.GetPacketId(), packetType);
}
}
}

Some files were not shown because too many files have changed in this diff Show More