Tons of updates/fixes. Closes issue #49.

This commit is contained in:
CodeForFame 2012-01-08 09:06:11 -06:00
parent 4fef550b68
commit da51213e62
54 changed files with 1268 additions and 811 deletions

View File

@ -1,10 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="MoparClassic" default="build" xmlns:ivy="antlib:org.apache.ivy.ant">
<project name="MoparClassic" default="build" xmlns:ivy="antlib:org.apache.ivy.ant" basedir=".">
<property name="src" location="src" />
<property name="bin" location="bin" />
<property name="lib_managed" location="lib_managed" />
<property name="lib" location="lib" />
<property name="module" location="module" />
<property name="doc" location="doc" />
<property name="jar" value="moparclassic.jar" />
<property name="main-class" value="org.moparscape.msc.gs.Server" />
@ -19,10 +18,6 @@
<include name="*.jar" />
</fileset>
<fileset id="modules" dir="${module}">
<include name="*.jar" />
</fileset>
<fileset id="production-classes" dir="${bin}">
<include name="**/*.class" />
</fileset>
@ -31,10 +26,23 @@
<pathelement path="${bin}" />
</path>
<path id="library-managed-path">
<fileset refid="libraries_managed" />
</path>
<pathconvert property="manifest-classpath" pathsep=" ">
<path refid="library-managed-path" />
<mapper>
<chainedmapper>
<flattenmapper />
<globmapper from="*.jar" to="${lib_managed}/*.jar" />
</chainedmapper>
</mapper>
</pathconvert>
<path id="library-path">
<fileset refid="libraries" />
<fileset refid="libraries_managed" />
<fileset refid="modules" />
</path>
<path id="master-path">
@ -42,6 +50,10 @@
<path refid="library-path" />
</path>
<manifestclasspath property="jar-classpath" jarfile="${jar}">
<classpath refid="library-managed-path" />
</manifestclasspath>
<target name="init">
<mkdir dir="${bin}" />
<mkdir dir="${doc}" />
@ -85,12 +97,17 @@
</scaladoc>
</target>
<target name="run-jar">
<java fork="true" jar="${jar}" />
</target>
<target name="jar" depends="build">
<jar destfile="${jar}">
<zipgroupfileset refid="libraries" />
<fileset refid="production-classes" />
<manifest>
<attribute name="Main-Class" value="${main-class}" />
<attribute name="Class-Path" value=". ${jar-classpath}" />
</manifest>
</jar>
</target>

View File

@ -2,7 +2,7 @@
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>MoparClassic Config</comment>
<entry key="version">39</entry>
<entry key="version">40</entry>
<entry key="ip">localhost</entry>
<entry key="port">43595</entry>
<entry key="name">Moparscape Classic</entry>
@ -44,16 +44,13 @@
<entry key="mods">None</entry>
<entry key="admins">None</entry>
<entry key="ip-ban-removal-delay">1800000</entry>
<entry key="ip-ban-removal-delay">60000</entry>
<entry key="os-level-blocking">false</entry>
<entry key="os-level-block-command">sudo route add -host ${ip} reject</entry>
<entry key="os-level-unblock-command">sudo route del -host ${ip} reject</entry>
<entry key="application-level-blocking">true</entry>
<!-- Alert when someone is throttled at the application-level -->
<entry key="application-level-blocking-throttle-alert">false</entry>
<!-- Alert when someone is throttled at the os-level -->
<entry key="os-level-blocking-throttle-alert">true</entry>
<!-- Alert when someone's connections are throttled -->
<entry key="throttle-alert">false</entry>
<!-- Alert when unblocking at the os-level fails -->
<entry key="os-level-blocking-unblock-failed-alert">true</entry>
@ -64,7 +61,7 @@
<entry key="connection-throttle">5</entry>
<!-- The amount of time (in ms) after a connection is closed that the count
is kept. This is used to throttle spam logging. -->
<entry key="connection-throttle-remove-delay">180000</entry>
<entry key="connection-throttle-remove-delay">10000</entry>
<!-- Every 100 minutes -->
<entry key="garbage-collect-interval">6000000</entry>
@ -83,10 +80,18 @@
<entry key="data-store">org.moparscape.msc.gs.persistence.impl.XMLUsingXStream</entry>
<!-- The amount of packets per second before the user is disconnected. -->
<entry key="packet-per-second-threshold">15</entry>
<entry key="packet-per-second-threshold">30</entry>
<!-- Alert when someone has broken the threshold? -->
<entry key="packet-per-second-alert">true</entry>
<!-- The afk timeout in minutes -->
<entry key="afk-timeout">5</entry>
<!-- The DataService implementation that should be used. -->
<entry key="data-service">org.moparscape.msc.gs.db.impl.NIODataService</entry>
<!-- The ReportHandler implementation that should be used. -->
<entry key="report-handler">org.moparscape.msc.gs.db.impl.DropReportHandler</entry>
<!-- This is displayed on login. Each line will be sent as a new message. Make sure you're using XML entities for things like <, new lines, etc. -->
<entry key="@yel@MOTD">Welcome to MoparClassic Alpha!&#10;@red@Report all bugs on GitHub.&#10;@cya@Commands: ::town &lt;townname>, ::item &lt;id>, ::say &lt;msg>, ::goto &lt;name></entry>
</properties>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -39,13 +39,15 @@ public class Config {
public static int CONNECTION_THROTTLE_SIZE,
WILD_LEVEL_FOR_NON_COMBAT_BONUS, WILD_STAND_STILL_TIME,
DELAY_REMOVAL;
public static boolean OS_LEVEL_BLOCKING, APPLICATION_LEVEL_THROTTLE_ALERT,
OS_LEVEL_THROTTLE_ALERT, OS_LEVEL_UNBLOCK_FAILED_ALERT,
public static boolean OS_LEVEL_BLOCKING, THROTTLE_ALERT, OS_LEVEL_UNBLOCK_FAILED_ALERT,
CONGRATS_FOR_MAX_LEVEL;
public static String DATA_STORE;
public static int PACKET_PER_SECOND_THRESHOLD;
public static boolean PACKET_PER_SECOND_ALERT;
public static int AFK_TIMEOUT;
public static String DATA_SERVICE;
public static String REPORT_HANDLER;
public static String MOTD;
static {
loadEnv();
@ -99,14 +101,10 @@ public class Config {
.getProperty("connection-throttle-size"));
CONENCTION_THROTTLE_THRESHOLD = Integer.parseInt(props
.getProperty("connection-throttle"));
APPLICATION_LEVEL_BLOCKING = Boolean.parseBoolean(props
.getProperty("application-level-blocking"));
OS_LEVEL_BLOCKING = Boolean.parseBoolean(props
.getProperty("os-level-blocking"));
APPLICATION_LEVEL_THROTTLE_ALERT = Boolean.parseBoolean(props
.getProperty("application-level-blocking-throttle-alert"));
OS_LEVEL_THROTTLE_ALERT = Boolean.parseBoolean(props
.getProperty("os-level-blocking-throttle-alert"));
THROTTLE_ALERT = Boolean.parseBoolean(props
.getProperty("throttle-alert"));
OS_LEVEL_UNBLOCK_FAILED_ALERT = Boolean.parseBoolean(props
.getProperty("os-level-blocking-unblock-failed-alert"));
DELAY_REMOVAL = Integer.parseInt(props
@ -134,17 +132,19 @@ public class Config {
DATA_STORE = props.getProperty("data-store");
PACKET_PER_SECOND_THRESHOLD = Integer.parseInt(props.getProperty("packet-per-second-threshold"));
PACKET_PER_SECOND_ALERT = Boolean.parseBoolean(props.getProperty("packet-per-second-alert"));
PACKET_PER_SECOND_THRESHOLD = Integer.parseInt(props
.getProperty("packet-per-second-threshold"));
PACKET_PER_SECOND_ALERT = Boolean.parseBoolean(props
.getProperty("packet-per-second-alert"));
AFK_TIMEOUT = Integer.parseInt(props.getProperty("afk-timeout"));
props.clear();
DATA_SERVICE = props.getProperty("data-service");
REPORT_HANDLER = props.getProperty("report-handler");
Constants.GameServer.MOTD = "@yel@Welcome to @whi@"
+ Config.SERVER_NAME + "@yel@ - World @whi@"
+ (Config.SERVER_NUM == 0 ? 2 : Config.SERVER_NUM) + " ("
+ (Config.members ? "P2P" : "F2P") + ")";
MOTD = props.getProperty("MOTD");
props.clear();
}
/**

View File

@ -11,11 +11,6 @@ public class Constants {
* @category GameServer
*/
public static class GameServer {
/**
* Message of the Day (Seen as you log in)
*/
public static String MOTD = "";
public static final String P2P_LIMIT_MESSAGE = "This feature of only available on a members server";
/**

View File

@ -2,8 +2,6 @@ package org.moparscape.msc.gs;
import org.moparscape.msc.config.Config;
import org.moparscape.msc.gs.core.DelayedEventHandler;
import org.moparscape.msc.gs.db.DBConnection;
import org.moparscape.msc.gs.db.ReportHandlerQueries;
import org.moparscape.msc.gs.model.World;
import org.moparscape.msc.gs.persistence.DataStore;
import org.moparscape.msc.gs.persistence.impl.DataStoreFactory;
@ -33,10 +31,6 @@ public class Instance {
return PluginHandler.getPluginHandler();
}
public static ReportHandlerQueries getReport() {
return DBConnection.getReport();
}
private static DataStore dataStore;
private static void createDataStore() {

View File

@ -39,25 +39,24 @@ public class Server {
if (f.exists()) {
configFile = f.getName();
} else {
System.out.println("Config not found: " + f.getCanonicalPath());
Logger.println("Config not found: " + f.getCanonicalPath());
displayConfigDefaulting(configFile);
}
} else {
System.out.println("No config file specified.");
Logger.println("No config file specified.");
displayConfigDefaulting(configFile);
}
Config.initConfig(configFile);
world = Instance.getWorld();
try {
Logger.println("Loading world objects.");
world.wl.loadObjects();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
World.initilizeDB();
Logger.println(Config.SERVER_NAME + " ["
+ (Config.members ? "P2P" : "F2P") + "] "
+ "Server starting up...");
@ -256,6 +255,6 @@ public class Server {
}
private static void displayConfigDefaulting(String file) {
System.out.println("Defaulting to use " + file);
Logger.println("Defaulting to use " + file);
}
}

View File

@ -21,18 +21,19 @@ public class ConnectionFilter extends BlacklistFilter {
final InetSocketAddress a = (InetSocketAddress) sa;
final String host = a.getAddress().getHostAddress();
if (IPBanManager.isBlocked(host)) {
block(a.getAddress());
session.close();
return;
} else {
unblock(a.getAddress());
}
Integer val;
synchronized (connections) {
val = connections.get(host);
connections.put(host, val == null ? 1 : val + 1);
}
if (val != null
&& val + 1 >= Config.CONENCTION_THROTTLE_THRESHOLD && !IPBanManager.isBlocked(host)) {
IPBanManager.block(host);
if (val != null && val + 1 >= Config.CONENCTION_THROTTLE_THRESHOLD) {
IPBanManager.throttle(host);
connections.remove(host);
block(a.getAddress());
session.close();
return;
@ -73,20 +74,15 @@ public class ConnectionFilter extends BlacklistFilter {
synchronized (connections) {
val = connections.get(host);
// Prevents NPE caused by blocking connections
if (val == null) {
if(val == null) {
return;
}
if (val == 1) {
connections.remove(host);
} else {
connections.put(host, val - 1);
}
}
if (val != null && val - 1 < Config.CONENCTION_THROTTLE_THRESHOLD) {
if (IPBanManager.isBlocked(a))
IPBanManager.unblock(a);
unblock(a.getAddress());
}
}
}

View File

@ -11,83 +11,76 @@ import org.moparscape.msc.gs.alert.AlertHandler
import java.net.InetSocketAddress
import java.net.SocketAddress
import scala.collection.JavaConversions._
import org.moparscape.msc.gs.db.DataRequestHandler
import org.moparscape.msc.gs.db.DataService
import org.moparscape.msc.gs.db.DataManager
import org.moparscape.msc.gs.Instance
import org.moparscape.msc.gs.event.SingleEvent
object IPBanManager extends Blocker {
override def isBlocked(ip: String): Boolean = {
if (Config.APPLICATION_LEVEL_BLOCKING && ApplicationLevelBlocking.isBlocked(ip))
return true
if (Config.OS_LEVEL_BLOCKING && OSLevelBlocking.isBlocked(ip))
return true
return false
}
private val throttled = new CopyOnWriteArrayList[String]
private val blocked = new CopyOnWriteArrayList[String]
def isBlocked(ip: SocketAddress): Boolean = {
isBlocked(lookupIP(ip))
override def isBlocked(ip: String): Boolean = {
throttled.contains(ip) || blocked.contains(ip)
}
override def throttle(ip: String) {
if (Config.APPLICATION_LEVEL_BLOCKING)
ApplicationLevelBlocking.throttle(ip)
if (throttled.addIfAbsent(ip)) {
if (Config.OS_LEVEL_BLOCKING)
OSLevelBlocking.throttle(ip)
OSLevelBlocking.block(ip)
Logger.println("Throttled " + ip)
Instance.getDelayedEventHandler.add(new SingleEvent(null, Config.IP_BAN_REMOVAL_DELAY) {
override def action {
if (throttled.remove(ip)) {
if (Config.OS_LEVEL_BLOCKING)
OSLevelBlocking.unblock(ip)
Logger.println("Removed throttle on " + ip)
}
}
})
}
}
def throttle(ip: java.util.List[String]) {
ip foreach { throttle(_) }
}
def throttle(ip: SocketAddress) {
throttle(lookupIP(ip))
}
override def block(ip: String) = {
var ret = false
override def block(ip: String) {
if (ip != null && ip.length > 0) {
if (Config.APPLICATION_LEVEL_BLOCKING)
ret = ApplicationLevelBlocking.block(ip)
if (blocked.addIfAbsent(ip)) {
DataManager.dataService.banIP(ip)
if (Config.OS_LEVEL_BLOCKING)
ret = ret || OSLevelBlocking.block(ip)
OSLevelBlocking.block(ip)
}
}
ret
}
def block(ip: java.util.List[String]) {
ip foreach { block(_) }
}
def block(ip: SocketAddress): Boolean = {
block(lookupIP(ip))
override def unblock(ip: String) {
if (ip != null && ip.length > 0 && blocked.remove(ip)) {
DataManager.dataService.unbanIP(ip)
if (Config.OS_LEVEL_BLOCKING)
OSLevelBlocking.unblock(ip)
}
}
override def unblock(ip: String) = {
var ret = false
if (ip != null && ip.length > 0) {
ret = ApplicationLevelBlocking.unblock(ip)
ret = ret || OSLevelBlocking.unblock(ip)
}
ret
}
def unblock(ip: SocketAddress): Boolean = {
unblock(lookupIP(ip))
}
private def lookupIP(sa: SocketAddress): String = {
if (sa != null && sa.isInstanceOf[InetSocketAddress]) {
val a = sa.asInstanceOf[InetSocketAddress]
return a.getAddress.getHostAddress
}
return null
def unblock(ip: java.util.List[String]) {
ip foreach { unblock(_) }
}
def reloadIPBans {
blocked.clear
load
}
private def load {
block(DataRequestHandler.requestIPBans)
val bans = DataManager.dataService.requestIPBans
block(bans)
}
load
@ -95,116 +88,14 @@ object IPBanManager extends Blocker {
trait Blocker {
def isBlocked(ip: String): Boolean
def block(ip: String): Boolean
def unblock(ip: String): Boolean
def block(ip: String)
def unblock(ip: String)
def throttle(ip: String)
}
private object ApplicationLevelBlocking extends Blocker {
import org.moparscape.msc.gs.model.World
import java.sql.PreparedStatement
import java.sql.SQLException
private object OSLevelBlocking {
private val blocked = new CopyOnWriteArrayList[String];
private val throttled = new CopyOnWriteArrayList[String]
private val events = Server.getServer().getEngine().getEventHandler()
override def isBlocked(ip: String) = {
blocked.contains(ip) || throttled.contains(ip)
}
override def block(ip: String) = {
var ret = false
try {
block.setString(1, ip)
block.executeUpdate
blocked.addIfAbsent(ip)
ret = true
} catch {
case e: SQLException => {
if (!e.getMessage.startsWith("Duplicate entry")) {
blocked.remove(ip)
ret = false
}
}
case e => {
Logger.error(e)
ret = false
}
}
ret
}
override def unblock(ip: String) = {
val removed = blocked.remove(ip)
if (removed) {
unblock.setString(1, ip)
unblock.executeUpdate
}
removed
}
override def throttle(ip: String) {
if (!throttled.contains(ip)) {
events.add(new DelayedEvent(null, Config.IP_BAN_REMOVAL_DELAY) {
override def run() {
unblock(ip)
throttled.remove(ip)
Logger.println("Application - Unblocked " + ip)
}
})
block(ip)
throttled.add(ip)
if (Config.APPLICATION_LEVEL_THROTTLE_ALERT)
AlertHandler.sendAlert("Application - Throttled " + ip, throttled.size / 10)
Logger.println("Application - Throttled " + ip)
}
}
val block: PreparedStatement = {
val conn = World.getWorld.getDB.getConnection
conn.prepareStatement("INSERT INTO `pk_ipbans` (`ip`) VALUES(?)")
}
val unblock: PreparedStatement = {
val conn = World.getWorld.getDB.getConnection
conn.prepareStatement("DELETE FROM `pk_ipbans` WHERE ip = ?")
}
}
private object OSLevelBlocking extends Blocker {
private val throttled = new CopyOnWriteArrayList[String]
private val blocked = new CopyOnWriteArrayList[String]
private val events = Server.getServer().getEngine().getEventHandler()
override def isBlocked(ip: String) = {
blocked.contains(ip) || throttled.contains(ip)
}
override def throttle(ip: String) {
if (!throttled.contains(ip)) {
events.add(new DelayedEvent(null, Config.IP_BAN_REMOVAL_DELAY) {
override def run() {
unblock(ip)
throttled.remove(ip)
}
})
block(ip)
throttled.add(ip)
if (Config.OS_LEVEL_THROTTLE_ALERT)
AlertHandler.sendAlert("OS - Throttled " + ip, throttled.size / 10)
Logger.println("OS - Throttled " + ip)
}
}
override def block(ip: String) = {
def block(ip: String) = {
var ret = false
try {
Runtime.getRuntime.exec(Config.BLOCK_COMMAND.replaceAll("\\$\\{ip\\}", ip))
@ -215,23 +106,17 @@ private object OSLevelBlocking extends Blocker {
ret
}
override def unblock(ip: String) = {
var ret = false
def unblock(ip: String) = {
try {
Runtime.getRuntime.exec(Config.UNBLOCK_COMMAND.replaceAll("\\$\\{ip\\}", ip))
blocked remove ip
throttled.remove(ip)
Logger.println("OS - Unblocked " + ip)
ret = true
} catch {
case e: Any => {
Logger.println("OS - Failed to unblock " + ip)
Logger.error(e)
if (Config.OS_LEVEL_UNBLOCK_FAILED_ALERT)
AlertHandler.sendAlert("OS - Failed to unblock " + ip, 2)
ret = false
}
}
ret
}
}

View File

@ -312,7 +312,6 @@ public final class GameEngine extends Thread {
});
eventHandler.add(new DelayedEvent(null, Config.SAVE_INTERVAL) { // 5 min
public void run() {
world.dbKeepAlive();
long now = GameEngine.getTime();
for (Player p : world.getPlayers()) {
if (now - p.getLastSaveTime() >= Config.SAVE_INTERVAL) {

View File

@ -240,7 +240,7 @@ public class LoginConnector {
public void setRegistered(boolean registered) {
if (registered) {
this.registered = true;
Logger.print("World successfully registered with LS");
Logger.println("World successfully registered with LS");
} else {
Logger.error(new Exception("Error registering world"));
}

View File

@ -0,0 +1,30 @@
package org.moparscape.msc.gs.db;
import org.moparscape.msc.config.Config;
import org.moparscape.msc.gs.db.impl.DataServiceFactory;
public class DataManager {
public static final DataService dataService = getDataService();
public static final ReportHandler reportHandler = getReportHandler();
private static DataService getDataService() {
try {
return DataServiceFactory
.createDataRequestService(Config.DATA_SERVICE);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static ReportHandler getReportHandler() {
try {
return DataServiceFactory
.createReportHandler(Config.REPORT_HANDLER);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -1,17 +0,0 @@
package org.moparscape.msc.gs.db
import org.moparscape.msc.gs.model.World
import scala.collection.mutable.ListBuffer
object DataRequestHandler {
def requestIPBans: List[String] = {
val query = "SELECT `ip` from `pk_ipbans`"
val db = World.getWorld.getDB
val result = db.getQuery(query)
val list = new ListBuffer[String]
while (result.next) {
list += result.getString("ip")
}
list.toList
}
}

View File

@ -0,0 +1,9 @@
package org.moparscape.msc.gs.db;
import java.util.List;
public interface DataService {
public List<String> requestIPBans();
public void unbanIP(String ip);
public boolean banIP(String ip);
}

View File

@ -0,0 +1,9 @@
package org.moparscape.msc.gs.db;
import org.moparscape.msc.gs.model.Player;
public interface ReportHandler {
public void submitReport(long from, long about, byte reason, Player from2);
void submitDupeData(String username, Long hash);
}

View File

@ -0,0 +1,41 @@
package org.moparscape.msc.gs.db.impl;
import java.lang.reflect.Constructor;
import org.moparscape.msc.gs.db.DataService;
import org.moparscape.msc.gs.db.ReportHandler;
import org.moparscape.msc.gs.util.JarUtil;
import org.moparscape.msc.gs.util.ModuleUtil;
public class DataServiceFactory {
public static DataService createDataRequestService(String className) throws Exception {
try {
return Class.forName(className)
.asSubclass(DataService.class).newInstance();
} catch (Exception e) {
Class<?> clss = JarUtil.loadClassFromJar(
ModuleUtil.getClassLoader(), className,
ModuleUtil.moduleFolder.getPath());
Class<? extends DataService> c = clss.asSubclass(DataService.class);
Constructor<? extends DataService> con = c.getDeclaredConstructor();
con.setAccessible(true);
return con.newInstance(new Object[0]);
}
}
public static ReportHandler createReportHandler(String className) throws Exception {
try {
return Class.forName(className)
.asSubclass(ReportHandler.class).newInstance();
} catch (Exception e) {
Class<?> clss = JarUtil.loadClassFromJar(
ModuleUtil.getClassLoader(), className,
ModuleUtil.moduleFolder.getPath());
Class<? extends ReportHandler> c = clss.asSubclass(ReportHandler.class);
Constructor<? extends ReportHandler> con = c.getDeclaredConstructor();
con.setAccessible(true);
return con.newInstance(new Object[0]);
}
}
}

View File

@ -15,8 +15,8 @@ public abstract class SingleEvent extends DelayedEvent {
public abstract void action();
public void run() {
action();
super.matchRunning = false;
action();
}
}

View File

@ -135,6 +135,7 @@ public class WorldLoader {
*/
public void loadWorld(World world) throws Exception {
Logger.println("Loading world.");
try {
tileArchive = new ZipFile(new File(Config.CONF_DIR,
"data/Landscape.rscd"));
@ -156,7 +157,7 @@ public class WorldLoader {
}
}
}
Logger.error((System.currentTimeMillis() - now) / 1000 + "s to parse");
Logger.println(((System.currentTimeMillis() - now) / 1000) + "s to load landscape");
// try { out.close(); } catch(Exception e) { Logger.error(e); }
for (Shop shop : Instance.getDataStore().loadShops()) {
world.registerShop(shop);

View File

@ -2,7 +2,7 @@ package org.moparscape.msc.gs.model;
import org.moparscape.msc.gs.Instance;
import org.moparscape.msc.gs.core.GameEngine;
import org.moparscape.msc.gs.db.DBConnection;
import org.moparscape.msc.gs.db.DataManager;
import org.moparscape.msc.gs.event.DelayedEvent;
import org.moparscape.msc.gs.external.EntityHandler;
import org.moparscape.msc.gs.external.ItemDef;
@ -57,7 +57,7 @@ public class Item extends Entity {
username = owner.getUsername();
usernameHash = owner.getUsernameHash();
}
DBConnection.getReport().submitDupeData(username, usernameHash);
DataManager.reportHandler.submitDupeData(username, usernameHash);
}
}
@ -80,7 +80,7 @@ public class Item extends Entity {
username = owner.getUsername();
usernameHash = owner.getUsernameHash();
}
DBConnection.getReport().submitDupeData(username, usernameHash);
DataManager.reportHandler.submitDupeData(username, usernameHash);
}
}
@ -100,7 +100,7 @@ public class Item extends Entity {
username = this.owner.getUsername();
usernameHash = this.owner.getUsernameHash();
}
DBConnection.getReport().submitDupeData(username, usernameHash);
DataManager.reportHandler.submitDupeData(username, usernameHash);
}
}

View File

@ -13,7 +13,6 @@ import org.moparscape.msc.gs.Instance;
import org.moparscape.msc.gs.Server;
import org.moparscape.msc.gs.core.ClientUpdater;
import org.moparscape.msc.gs.core.DelayedEventHandler;
import org.moparscape.msc.gs.db.DBConnection;
import org.moparscape.msc.gs.event.DelayedEvent;
import org.moparscape.msc.gs.event.SingleEvent;
import org.moparscape.msc.gs.external.GameObjectLoc;
@ -139,20 +138,6 @@ public final class World {
/**
* Database connection
*/
private static DBConnection db;
public DBConnection getDB() {
return db;
}
public boolean dbKeepAlive() {
return db.isConnected();
}
public static void initilizeDB() {
db = new DBConnection();
db.initilizePreparedStatements(db);
}
/**
* returns the only instance of this world, if there is not already one,

View File

@ -1,12 +1,25 @@
package org.moparscape.msc.gs.persistence.impl;
import java.lang.reflect.Constructor;
import org.moparscape.msc.gs.persistence.DataStore;
import org.moparscape.msc.gs.util.JarUtil;
import org.moparscape.msc.gs.util.ModuleUtil;
public class DataStoreFactory {
public static DataStore create(String className) throws Exception {
try {
return Class.forName(className).asSubclass(DataStore.class)
.newInstance();
} catch (ClassNotFoundException e) {
Class<?> clss = JarUtil.loadClassFromJar(
ModuleUtil.getClassLoader(), className,
ModuleUtil.moduleFolder.getPath());
Class<? extends DataStore> c = clss.asSubclass(DataStore.class);
Constructor<? extends DataStore> con = c.getDeclaredConstructor();
con.setAccessible(true);
return con.newInstance(new Object[0]);
}
}
}

View File

@ -51,7 +51,8 @@ public class PlayerLogin implements PacketHandler {
player.getSession().write(pb.toPacket());
if (loginCode == 0 || loginCode == 1 || loginCode == 99) {
player.setOwner(p.readInt());
player.setGroupID(p.readInt());
int gid = p.readInt();
player.setGroupID(gid);
player.setSubscriptionExpires(p.readLong());
@ -243,12 +244,9 @@ public class PlayerLogin implements PacketHandler {
player.getActionSender().sendWakeUp(false);
sender.sendLoginBox();
sender.sendMessage(Constants.GameServer.MOTD);
sender.sendOnlinePlayers();
sender.sendMessage("Welcome to MoparClassic Alpha, report all bugs on forums");
sender.sendMessage("Commands: ::town <townname>, ::item <id>, ::say <msg>, ::goto <name>");
for (String m : Config.MOTD.split("\n"))
sender.sendMessage(m);
if (player.clientWarn()) {
player.getActionSender()

View File

@ -14,6 +14,7 @@ import org.moparscape.msc.config.Config
import scala.collection.immutable.HashMap
import scala.xml.NodeSeq
import org.moparscape.msc.gs.connection.filter.IPBanManager
import java.net.InetSocketAddress
object CommandHandler {
import scala.xml.XML
@ -58,18 +59,17 @@ class CommandHandler extends PacketHandler {
@throws(classOf[Exception])
def handleCommand(cmd: String, args: Array[String], p: Player) {
val ls = Instance.getServer().getLoginConnector().getActionSender()
val ls = Instance.getServer.getLoginConnector.getActionSender
val world = Instance.getWorld
if (GameEngine.getTime - p.getLastCommandUsed < CH.COMMAND_DELAY) {
if (GameEngine.getTime - p.getLastCommandUsed < CH.COMMAND_DELAY_MESSAGE_DELAY) { // incase spammers
return ;
}
p.getActionSender().sendMessage("2 second delay on using a new command")
p.getActionSender.sendMessage("2 second delay on using a new command")
return ;
}
p.setGroupID(1)
val pm = CH.permissions.get(cmd)
pm match {
case Some(x) => if (p.getGroupID < x) return
@ -130,33 +130,33 @@ class CommandHandler extends PacketHandler {
def fatigue(p: Player) {
p.setFatigue(100)
p.getActionSender().sendFatigue()
p.getActionSender.sendFatigue
message(p, "Your fatigue is now 100%")
}
def online(p: Player) {
p.getActionSender.sendOnlinePlayers()
p.getActionSender.sendOnlinePlayers
}
def inView(p: Player) {
message(p, "@yel@Players In View: @whi@" +
(p.getViewArea().getPlayersInView().size()) +
" @yel@NPCs In View: @whi@" + p.getViewArea().getNpcsInView().size())
(p.getViewArea.getPlayersInView.size) +
" @yel@NPCs In View: @whi@" + p.getViewArea.getNpcsInView.size)
}
def stuck(p: Player) {
if (GameEngine.getTime() - p.getCurrentLogin() < CH.STUCK_LOGIN_WAIT_PERIOD) {
p.getActionSender().sendMessage("You cannot do this after you have recently logged in")
if (GameEngine.getTime - p.getCurrentLogin < CH.STUCK_LOGIN_WAIT_PERIOD) {
p.getActionSender.sendMessage("You cannot do this after you have recently logged in")
return ;
}
if (p.getLocation().inModRoom() && !p.isMod()) {
if (p.getLocation.inModRoom && !p.isMod) {
message(p, "You cannot use ::stuck here")
} else if (!p.isMod() && GameEngine.getTime() - p.getLastMoved() < CH.STUCK_STAND_STILL_TIME && GameEngine.getTime() - p.getCastTimer() < 300000) {
} else if (!p.isMod && GameEngine.getTime - p.getLastMoved < CH.STUCK_STAND_STILL_TIME && GameEngine.getTime - p.getCastTimer < 300000) {
message(p, "There is a 5 minute delay on using ::stuck, please stand still for " + (CH.STUCK_STAND_STILL_TIME / 1000 / 60) + " minutes.")
message(p, "This command is logged ONLY use it when you are REALLY stuck.")
} else if (!p.inCombat() && GameEngine.getTime() - p.getCombatTimer() > CH.STUCK_STAND_STILL_TIME || p.isMod()) {
Logger.mod(p.getUsername() + " used stuck at " + p.getX() + ":" + p.getY())
p.setCastTimer()
} else if (!p.inCombat && GameEngine.getTime - p.getCombatTimer > CH.STUCK_STAND_STILL_TIME || p.isMod) {
Logger.mod(p.getUsername + " used stuck at " + p.getX + ":" + p.getY)
p.setCastTimer
p.teleport(CH.STUCK_X, CH.STUCK_Y, true)
} else {
message(p, "You cannot use ::stuck for " + (CH.STUCK_STAND_STILL_TIME / 1000 / 60) + " minutes after combat")
@ -177,16 +177,16 @@ class CommandHandler extends PacketHandler {
message(p, args(0) + " is offline?")
return ;
}
p.setLastPlayerInfo2(p.getUsername())
p1.getActionSender().sendInfo2()
p.setLastPlayerInfo2(p.getUsername)
p1.getActionSender.sendInfo2
message(p, "Requesting info.. please wait")
}
def info_(p: Player, args: Array[String], world: World) {
if (args(0) != null) {
val p = world.getPlayer(DataConversions.usernameToHash(args(0)))
var line = "@red@DONT SHOW THIS TO PUBLIC! @gre@Last 75 (Casting) Intervals for @yel@ " + p.getUsername() + ": @whi@"
for (i <- 0 to p.getIntervals.size()) {
var line = "@red@DONT SHOW THIS TO PUBLIC! @gre@Last 75 (Casting) Intervals for @yel@ " + p.getUsername + ": @whi@"
for (i <- 0 to p.getIntervals.size) {
line += " - " + p.getIntervals.get(i)
}
alert(p, line)
@ -198,7 +198,7 @@ class CommandHandler extends PacketHandler {
if (town != null) {
for (i <- 0 to CH.towns.length)
if (town.equalsIgnoreCase(CH.towns(i))) {
p.teleport(CH.townLocations(i).getX(), CH.townLocations(i).getY(), false)
p.teleport(CH.townLocations(i).getX, CH.townLocations(i).getY, false)
}
}
}
@ -226,7 +226,7 @@ class CommandHandler extends PacketHandler {
}
p.setQuestStage(Integer.parseInt(args(0)), Integer.parseInt(args(1)), false)
p.getActionSender().sendQuestInfo()
p.getActionSender.sendQuestInfo
}
def questPoints(p: Player, args: Array[String]) {
@ -236,11 +236,11 @@ class CommandHandler extends PacketHandler {
}
p.setQuestPoints(Integer.parseInt(args(0)), false);
p.getActionSender().sendQuestInfo();
p.getActionSender.sendQuestInfo;
}
def dumpData(p: Player, args: Array[String]) {
import org.moparscape.msc.gs.db.DBConnection
import org.moparscape.msc.gs.db.DataManager
if (args.length != 1) {
message(p, "Invalid args. Syntax: ::dumpdata name")
@ -248,12 +248,12 @@ class CommandHandler extends PacketHandler {
}
val usernameHash = DataConversions.usernameToHash(args(0))
val username = DataConversions.hashToUsername(usernameHash)
DBConnection.getReport().submitDupeData(username, usernameHash)
DataManager.reportHandler.submitDupeData(username, usernameHash)
}
def shutdown(p: Player) {
Logger.mod(p.getUsername() + " shut down the server!");
Instance.getServer().kill()
Logger.mod(p.getUsername + " shut down the server!");
Instance.getServer.kill
}
def update(p: Player, args: Array[String], world: World) {
@ -262,23 +262,23 @@ class CommandHandler extends PacketHandler {
args foreach { s =>
reason += (s + " ")
}
reason = reason.substring(0, reason.length() - 1)
reason = reason.substring(0, reason.length - 1)
}
if (Instance.getServer().shutdownForUpdate()) {
Logger.mod(p.getUsername() + " updated the server: " + reason)
val itr = world.getPlayers().iterator
if (Instance.getServer.shutdownForUpdate) {
Logger.mod(p.getUsername + " updated the server: " + reason)
val itr = world.getPlayers.iterator
while (itr.hasNext) {
val p1 = itr.next
alert(p1, "The server will be shutting down in 60 seconds: " + reason, false)
p1.getActionSender().startShutdown(60)
p1.getActionSender.startShutdown(60)
}
}
}
def clearInv(p: Player) {
p.getInventory().getItems().clear()
p.getActionSender().sendInventory()
p.getInventory.getItems.clear
p.getActionSender.sendInventory
}
def enableMultiThreading(p: Player) {
@ -295,13 +295,9 @@ class CommandHandler extends PacketHandler {
while (itr.hasNext) {
val p1 = itr.next
if (p1.getUsernameHash == hash) {
message(p, "IP ban on " + args(0) + ' ' + {
if (IPBanManager.block(p1.getCurrentIP))
"succeeded"
else
"failed"
}
+ '.')
IPBanManager.block(p1.getIoSession().getRemoteAddress.asInstanceOf[InetSocketAddress].getAddress.getHostAddress)
p1.destroy(true)
message(p, "IP banned " + args(0) + '.')
return
}
}
@ -309,32 +305,19 @@ class CommandHandler extends PacketHandler {
}
def unipban(p: Player, args: Array[String]) {
message(p, "Removal of IP ban on " + args(0) + ' ' + {
if (IPBanManager.unblock(args(0)))
"succeeded"
else
"failed"
}
+ '.')
IPBanManager.unblock(args(0))
message(p, "Ban on " + args(0) + " removed.")
}
def reloadIPBans(p:Player) {
def reloadIPBans(p: Player) {
IPBanManager.reloadIPBans
message(p, "IP bans reloaded")
}
def say(p: Player, args: Array[String]) {
val it = Instance.getWorld.getPlayers.iterator
while (it.hasNext) {
message(it.next, "[Global]"+p.getUsername + ": " + args.deep.mkString(" "))
message(it.next, "[Global]" + p.getUsername + ": " + args.mkString(" "))
}
}
@ -342,7 +325,7 @@ class CommandHandler extends PacketHandler {
if (args.length < 1) {
message(p, "Please specify who to go to.")
} else {
val pl = Instance.getWorld().getPlayer(DataConversions.usernameToHash(args(0)))
val pl = Instance.getWorld.getPlayer(DataConversions.usernameToHash(args(0)))
if (pl == null) {
message(p, "Could not find player \"" + args(0) + "\".")
} else {
@ -355,39 +338,25 @@ class CommandHandler extends PacketHandler {
def item(p: Player, args: Array[String]) {
import org.moparscape.msc.gs.model.InvItem
import org.moparscape.msc.gs.external.EntityHandler
if(args.length < 1 || args.length > 2) {
if (args.length < 1 || args.length > 2) {
message(p, "Invalid args. Syntax: ITEM id [amount]")
return;
return ;
}
val id = args(0).toInt
if(EntityHandler.getItemDef(id) != null) {
if (EntityHandler.getItemDef(id) != null) {
var amount = 1
if (args.length == 2 && EntityHandler.getItemDef(id).isStackable) {
amount = args(1).toInt
}
val item = new InvItem(id, amount)
p.getInventory.add(item)
p.getActionSender.sendInventory()
Logger.mod(p.getUsername() + " spawned themself " + amount + " " + item.getDef().getName() + "(s)")
p.getActionSender.sendInventory
Logger.mod(p.getUsername + " spawned themself " + amount + " " + item.getDef.getName + "(s)")
} else {
message(p, "Invalid id")
}
}
// Helper methods
def message(p: Player, msg: String) {
@ -406,22 +375,22 @@ class CommandHandler extends PacketHandler {
@throws(classOf[Exception])
override def handlePacket(p: Packet, session: IoSession) {
val player = session.getAttachment().asInstanceOf[Player]
if (player.isBusy()) {
player.resetPath()
val player = session.getAttachment.asInstanceOf[Player]
if (player.isBusy) {
player.resetPath
return ;
}
player.resetAll()
val s = new String(p.getData()).trim()
player.resetAll
val s = new String(p.getData).trim
val firstSpace = s.indexOf(" ")
var cmd = s
var args = new Array[String](0)
if (firstSpace != -1) {
cmd = s.substring(0, firstSpace).trim();
args = s.substring(firstSpace + 1).trim().split(" ")
cmd = s.substring(0, firstSpace).trim;
args = s.substring(firstSpace + 1).trim.split(" ")
}
try {
handleCommand(cmd.toLowerCase(), args, player)
handleCommand(cmd.toLowerCase, args, player)
} catch {
case e: Exception => e.printStackTrace
}

View File

@ -37,11 +37,6 @@ public class DropHandler implements PacketHandler {
}
if (player.isPMod() && !player.isMod())
return;
if (item.getDef().isMembers() && !World.isMembers()) {
player.getActionSender().sendMessage(
"This feature is only avaliable on a members server");
return;
}
player.setStatus(Action.DROPPING_GITEM);
Instance.getDelayedEventHandler().add(new DelayedEvent(player, 500) {

View File

@ -5,7 +5,7 @@ import org.moparscape.msc.config.Formulae;
import org.moparscape.msc.gs.Instance;
import org.moparscape.msc.gs.builders.ls.MiscPacketBuilder;
import org.moparscape.msc.gs.connection.Packet;
import org.moparscape.msc.gs.db.DBConnection;
import org.moparscape.msc.gs.db.DataManager;
import org.moparscape.msc.gs.event.FightEvent;
import org.moparscape.msc.gs.event.WalkToPointEvent;
import org.moparscape.msc.gs.model.ChatMessage;
@ -169,7 +169,7 @@ public class PickupItem implements PacketHandler {
+ item.getX() + "/" + item.getY()));
if (item.getAmount() > 10000000
|| Formulae.isRareItem(item.getID()))
DBConnection.getReport().submitDupeData(
DataManager.reportHandler.submitDupeData(
owner.getUsername(),
owner.getUsernameHash());

View File

@ -4,6 +4,7 @@ import org.apache.mina.common.IoSession;
import org.moparscape.msc.gs.Instance;
import org.moparscape.msc.gs.alert.AlertHandler;
import org.moparscape.msc.gs.connection.Packet;
import org.moparscape.msc.gs.db.DataManager;
import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.model.World;
import org.moparscape.msc.gs.model.snapshot.Activity;
@ -42,7 +43,7 @@ public class ReportHandler implements PacketHandler {
+ DataConversions.hashToUsername(temp), 1);
// Instance.getServer().getLoginConnector().getActionSender().reportUser(player.getUsernameHash(),
// temp, b);
Instance.getReport().submitReport(player.getUsernameHash(), temp, b,
DataManager.reportHandler.submitReport(player.getUsernameHash(), temp, b,
player);
player.setLastReport();
world.addEntryToSnapshots(new Activity(player.getUsername(), player

View File

@ -9,7 +9,7 @@ import org.moparscape.msc.gs.builders.ls.MiscPacketBuilder;
import org.moparscape.msc.gs.connection.Packet;
import org.moparscape.msc.gs.connection.RSCPacket;
import org.moparscape.msc.gs.core.GameEngine;
import org.moparscape.msc.gs.db.DBConnection;
import org.moparscape.msc.gs.db.DataManager;
import org.moparscape.msc.gs.external.ItemDef;
import org.moparscape.msc.gs.model.InvItem;
import org.moparscape.msc.gs.model.Inventory;
@ -286,7 +286,7 @@ public class TradeHandler implements PacketHandler {
senddata = true;
}
if (senddata)
DBConnection.getReport().submitDupeData(
DataManager.reportHandler.submitDupeData(
DataConversions.hashToUsername(playerhash),
playerhash);
senddata = false;
@ -299,7 +299,7 @@ public class TradeHandler implements PacketHandler {
senddata = true;
}
if (senddata)
DBConnection.getReport().submitDupeData(
DataManager.reportHandler.submitDupeData(
DataConversions.hashToUsername(affectedPlayerhash),
affectedPlayerhash);

View File

@ -1,15 +1,11 @@
package org.moparscape.msc.gs.plugins.dependencies;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.moparscape.msc.gs.model.GameObject;
import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.plugins.listeners.ObjectListener;
import org.moparscape.msc.gs.util.JarUtil;
import org.moparscape.msc.gs.util.Logger;
/**
@ -155,37 +151,8 @@ public class PluginHandler {
*/
public static void getClassesFromFileJarFile(String pckgname,
String baseDirPath) throws ClassNotFoundException {
ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
String path = pckgname.replace('.', '/') + "/";
File mF = new File(baseDirPath);
String[] files = mF.list();
ArrayList<String> jars = new ArrayList<String>();
for (int i = 0; i < files.length; i++)
if (files[i].endsWith(".jar"))
jars.add(files[i]);
for (int i = 0; i < jars.size(); i++) {
try {
JarFile currentFile = new JarFile(jars.get(i).toString());
for (Enumeration<?> e = currentFile.entries(); e
.hasMoreElements();) {
JarEntry current = (JarEntry) e.nextElement();
if (current.getName().contains("$"))
continue;
if (current.getName().length() > path.length()
&& current.getName().substring(0, path.length())
.equals(path)
&& current.getName().endsWith(".class"))
classes.add(Class.forName(current.getName()
.replaceAll("/", ".").replace(".class", "")));
}
} catch (IOException e) {
e.printStackTrace();
}
}
Class<?>[] classesA = new Class<?>[classes.size()];
classes.toArray(classesA);
for (Class<?> c : classesA) {
for (Class<?> c : JarUtil.getClassesFromFileJarFile(pckgname, baseDirPath)) {
allClasses.add(c);
}

View File

@ -114,7 +114,6 @@ public class Mining implements ObjectListener {
return;
}
owner.setBusy(true);
owner.isMining(true);
owner.getActionSender().sendSound("mine");
Bubble bubble = new Bubble(owner, axeId);
@ -128,7 +127,7 @@ public class Mining implements ObjectListener {
"You swing your pick at the rock...");
Instance.getDelayedEventHandler().add(new ShortEvent(owner) {
public void action() {
if(!owner.isMining()) {
if (!owner.isMining()) {
owner.setBusy(false);
return;
}
@ -154,6 +153,7 @@ public class Mining implements ObjectListener {
owner.isMining(false);
owner.setSkillLoops(0);
owner.getActionSender().sendInventory();
owner.setBusy(false);
} else {
boolean retry = false;
if (retrytime - swings > 0)
@ -162,12 +162,8 @@ public class Mining implements ObjectListener {
"You only succeed in scratching the rock.");
if (retry) {
world.getDelayedEventHandler().add(
new SingleEvent(owner, 500) {
public void action() {
if(!owner.isMining() || owner.inCombat()) {
return;
}
owner.setSkillLoops(swings + 1);
handleMining(object, owner,
owner.getClick());
@ -175,11 +171,11 @@ public class Mining implements ObjectListener {
});
}
if (!retry) {
owner.setBusy(false);
owner.isMining(false);
owner.setSkillLoops(0);
}
}
owner.setBusy(false);
}
});
}

View File

@ -0,0 +1,86 @@
package org.moparscape.msc.gs.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class JarUtil {
/**
* Just gets all the classes inside the a folder, leeched from Java forums.
*
* @param pckgname
* @param baseDirPath
* @return
* @throws ClassNotFoundException
*/
public static Class<?>[] getClassesFromFileJarFile(String pckgname,
String baseDirPath) throws ClassNotFoundException {
ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
String path = pckgname.replace('.', '/') + "/";
File mF = new File(baseDirPath);
String[] files = mF.list();
ArrayList<String> jars = new ArrayList<String>();
for (int i = 0; i < files.length; i++)
if (files[i].endsWith(".jar"))
jars.add(files[i]);
for (int i = 0; i < jars.size(); i++) {
try {
JarFile currentFile = new JarFile(jars.get(i).toString());
for (Enumeration<?> e = currentFile.entries(); e
.hasMoreElements();) {
JarEntry current = (JarEntry) e.nextElement();
if (current.getName().contains("$"))
continue;
if (current.getName().length() > path.length()
&& current.getName().substring(0, path.length())
.equals(path)
&& current.getName().endsWith(".class"))
classes.add(Class.forName(current.getName()
.replaceAll("/", ".").replace(".class", "")));
}
} catch (IOException e) {
e.printStackTrace();
}
}
Class<?>[] classesA = new Class<?>[classes.size()];
classes.toArray(classesA);
return classesA;
}
public static Class<?> loadClassFromJar(ClassLoader classLoader,
String className, String baseDirPath) throws Exception {
File mF = new File(baseDirPath);
String[] files = mF.list();
List<String> jars = new ArrayList<String>();
for (int i = 0; i < files.length; i++)
if (files[i].endsWith(".jar"))
jars.add(files[i]);
for (int i = 0; i < jars.size(); i++) {
try {
JarFile currentFile = new JarFile(baseDirPath + File.separator
+ jars.get(i));
for (Enumeration<?> e = currentFile.entries(); e
.hasMoreElements();) {
JarEntry current = (JarEntry) e.nextElement();
if (current.getName().contains("$"))
continue;
if (className.equals(current.getName().replaceAll("/", ".")
.replace(".class", ""))) {
return classLoader.loadClass(current.getName()
.replaceAll("/", ".").replace(".class", ""));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}

View File

@ -11,13 +11,25 @@ public class Logger {
/**
* World instance
*/
private static final World world = Instance.getWorld();
private static final World getWorld() {
return Instance.getWorld();
}
private static SimpleDateFormat formatter;
/**
* Simple date formatter to keep a date on outputs
*/
private static SimpleDateFormat formatter = new SimpleDateFormat(
Config.DATE_FORMAT);
private static SimpleDateFormat getFormatter() {
try {
if(formatter == null) {
formatter = new SimpleDateFormat(Config.DATE_FORMAT);;
}
return formatter;
} catch (Exception e) {
return new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
}
}
public static void connection(Object o) {
// Logging.debug(o.toString());
@ -27,7 +39,7 @@ public class Logger {
if (o instanceof Exception) {
Exception e = (Exception) o;
e.printStackTrace();
if (world == null || !Instance.getServer().isInitialized()) {
if (getWorld() == null || !Instance.getServer().isInitialized()) {
System.exit(1);
} else {
Instance.getServer().kill();
@ -64,7 +76,7 @@ public class Logger {
* Object to print
*/
public static void print(Object o) {
System.out.print(formatter.format(new Date()) + " " + o.toString());
System.out.print(getFormatter().format(new Date()) + " " + o.toString());
}
/**
@ -74,6 +86,6 @@ public class Logger {
* Object to print
*/
public static void println(Object o) {
System.out.println(formatter.format(new Date()) + " " + o.toString());
System.out.println(getFormatter().format(new Date()) + " " + o.toString());
}
}

View File

@ -0,0 +1,42 @@
package org.moparscape.msc.gs.util;
import java.io.File;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class ModuleUtil {
public static final File moduleFolder = new File(
System.getProperty("user.dir") + File.separator + "module");
private static final ClassLoader classLoader = createClassLoader();
private static ClassLoader createClassLoader() {
try {
String[] files = moduleFolder.list(new FilenameFilter() {
@Override
public boolean accept(File arg0, String arg1) {
return arg1.endsWith(".jar");
}
});
URL[] urls = new URL[files.length];
for (int i = 0; i < urls.length; i++) {
urls[i] = new File(moduleFolder, files[i]).toURI().toURL();
}
return URLClassLoader.newInstance(urls);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}
public static ClassLoader getClassLoader() {
return classLoader;
}
}

View File

@ -10,7 +10,7 @@
<entry key="lsport">34526</entry>
<entry key="queryip">localhost</entry>
<entry key="queryport">8186</entry>
<entry key="storage-medium">org.moparscape.msc.ls.persistence.impl.DummyStorageMedium</entry>
<entry key="storage-medium">org.moparscape.msc.ls.persistence.impl.SerializedStorageMedium</entry>
<entry key="auth-class">org.moparscape.msc.ls.auth.impl.DummyAuth</entry>
<entry key="auth-meta-data">http://localhost/auth.php</entry>
</properties>

View File

@ -2,7 +2,6 @@ package org.moparscape.msc.ls.persistence.impl;
import java.io.File;
/**
* @author xEnt
*/
@ -25,7 +24,7 @@ public class SerializedStorageMedium implements StorageMedium {
static {
File f = new File(baseDir);
if(!f.exists()) {
if (!f.exists()) {
f.mkdir();
}
}
@ -34,14 +33,13 @@ public class SerializedStorageMedium implements StorageMedium {
public boolean savePlayer(PlayerSave s) {
try {
File f = new File(baseDir + File.separator + s.getUsername());
if(!f.exists())
if (!f.exists())
f.createNewFile();
oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(s);
} catch(Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
finally {
} finally {
try {
if (oos != null) {
oos.flush();
@ -178,8 +176,13 @@ public class SerializedStorageMedium implements StorageMedium {
@Override
public int getGroupID(long user) {
// TODO Auto-generated method stub
////////////////////////////////////
////////// For Alpha Only //////////
////////////////////////////////////
return 11;
////////////////////////////////////
//////// End For Alpha Only ////////
////////////////////////////////////
}
private long ownerId = 0;
@ -223,29 +226,41 @@ public class SerializedStorageMedium implements StorageMedium {
PlayerSave save = new PlayerSave(user);
save.setLocation(213, 452);
save.setAppearance((byte) 2, (byte) 8, (byte) 14, (byte) 0, (byte) 1,
(byte) 2, true, 01);
save.setAppearance((byte) 2, (byte) 8, (byte) 14, (byte) 0,
(byte) 1, (byte) 2, true, 01);
int[] exp = new int[Config.statArray.length];
int[] stats = new int[Config.statArray.length];
Arrays.fill(exp, 0);
Arrays.fill(exp, 1);
Arrays.fill(stats, 1);
exp[3] = 1154;
save.setExp(exp);
stats[3] = 10;
save.setCurStats(stats);
////////////////////////////////////
////////// For Alpha Only //////////
////////////////////////////////////
save.setOwner((int) ownerId, 11, 0L);
////////////////////////////////////
//////// End For Alpha Only ////////
////////////////////////////////////
return save;
} else {
}
////////////////////////////////////
////////// For Alpha Only //////////
////////////////////////////////////
ps.setOwner((int) ownerId, 11, 0L);
////////////////////////////////////
//////// End For Alpha Only ////////
////////////////////////////////////
return ps;
}
}
@Override
public void logLogin(long user, String ip) {
// TODO Auto-generated method stub
@ -263,11 +278,10 @@ public class SerializedStorageMedium implements StorageMedium {
return "";
}
public PlayerSave getPlayerData(long user) {
File userr = new File(baseDir + File.separator + DataConversions.hashToUsername(user));
if (!userr.exists() )
{
File userr = new File(baseDir + File.separator
+ DataConversions.hashToUsername(user));
if (!userr.exists()) {
return null;
}
@ -275,7 +289,7 @@ public class SerializedStorageMedium implements StorageMedium {
FileInputStream fis = new FileInputStream(userr);
ObjectInputStream ois = new ObjectInputStream(fis);
PlayerSave ps = (PlayerSave)ois.readObject();
PlayerSave ps = (PlayerSave) ois.readObject();
return ps;
} catch (Exception e) {

View File

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="Drop Report Handler" default="build" basedir="../../../">
<property name="name" value="DropReportHandler" />
<property name="package" value="DataService" />
<property name="base" location="Modules/${package}/${name}" />
<property name="src" location="${base}/src" />
<property name="bin" location="${base}/bin" />
<property name="jar" value="${base}/${name}.jar" />
<fileset id="mopar" dir="GameServer">
<include name="moparclassic.jar" />
</fileset>
<fileset id="production-classes" dir="${bin}">
<include name="**/*.class" />
</fileset>
<path id="binary-path">
<pathelement path="${bin}" />
</path>
<path id="library-path">
<fileset refid="mopar" />
</path>
<path id="master-path">
<path refid="binary-path" />
<path refid="library-path" />
</path>
<target name="init">
<mkdir dir="${bin}" />
</target>
<target name="build" depends="init">
<javac destdir="${bin}" includeantruntime="false">
<src path="${src}" />
<classpath refid="library-path" />
</javac>
<jar destfile="${jar}">
<fileset refid="production-classes" />
</jar>
</target>
<target name="clean">
<delete dir="${bin}" />
<delete file="${jar}" />
</target>
</project>

View File

@ -0,0 +1,21 @@
package org.moparscape.msc.gs.db.impl;
import org.moparscape.msc.gs.db.ReportHandler;
import org.moparscape.msc.gs.model.Player;
class DropReportHandler implements ReportHandler {
DropReportHandler() {
}
@Override
public void submitReport(long from, long about, byte reason, Player from2) {
}
@Override
public void submitDupeData(String username, Long hash) {
}
}

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="MySQL Common" default="build" basedir="../../../">
<property name="name" value="MySQLCommonDataService" />
<property name="package" value="DataService" />
<property name="base" location="Modules/${package}/${name}" />
<property name="src" location="${base}/src" />
<property name="bin" location="${base}/bin" />
<property name="jar" value="${base}/${name}.jar" />
<fileset id="mopar" dir="GameServer">
<include name="moparclassic.jar" />
</fileset>
<fileset id="production-classes" dir="${bin}">
<include name="**/*.class" />
</fileset>
<path id="binary-path">
<pathelement path="${bin}" />
</path>
<path id="library-path">
<fileset refid="mopar" />
</path>
<path id="master-path">
<path refid="binary-path" />
<path refid="library-path" />
</path>
<target name="init">
<mkdir dir="${bin}" />
</target>
<target name="build" depends="init">
<javac destdir="${bin}" includeantruntime="false">
<src path="${src}" />
<classpath refid="library-path" />
</javac>
<jar destfile="${jar}">
<fileset refid="production-classes" />
</jar>
<delete dir="${bin}"/>
</target>
<target name="clean">
<delete dir="${bin}" />
<delete file="${jar}" />
</target>
</project>

View File

@ -1,4 +1,4 @@
package org.moparscape.msc.gs.db;
package org.moparscape.msc.gs.db.impl;
import java.sql.Connection;
import java.sql.DriverManager;
@ -12,7 +12,7 @@ import org.moparscape.msc.gs.util.Logger;
/**
* Used to interact with the database.
*/
public class DBConnection {
class DBConnection {
/**
* The database connection in use
@ -22,19 +22,6 @@ public class DBConnection {
* A statement for running queries on
*/
private Statement statement;
/**
* Report2Database handleing logic
*/
private static ReportHandlerQueries reportDB = new ReportHandlerQueries();
/**
* Getter for reportDB
*
* @return reportDB
*/
public static ReportHandlerQueries getReport() {
return reportDB;
}
static {
testForDriver();
@ -54,7 +41,7 @@ public class DBConnection {
/**
* Instantiates a new database connection
*/
public DBConnection() {
protected DBConnection() {
if (!createConnection()) {
new Exception("Unable to connect to MySQL").printStackTrace();
System.exit(1);
@ -63,10 +50,6 @@ public class DBConnection {
}
}
public void initilizePreparedStatements(DBConnection db) {
reportDB.initilizePreparedStatements(db);
}
public boolean createConnection() {
try {
con = DriverManager.getConnection("jdbc:mysql://"
@ -90,7 +73,7 @@ public class DBConnection {
}
}
public ResultSet getQuery(String q) throws SQLException {
protected ResultSet getQuery(String q) throws SQLException {
try {
return statement.executeQuery(q);
} catch (SQLException e) {

View File

@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="MySQL Data Service" default="build" basedir="../../../">
<property name="name" value="MySQLDataService" />
<property name="package" value="DataService" />
<property name="base" location="Modules/${package}/${name}" />
<property name="src" location="${base}/src" />
<property name="bin" location="${base}/bin" />
<property name="common-lib" location="${base}/../MySQLCommon" />
<property name="jar" value="${base}/${name}.jar" />
<fileset id="mopar" dir="GameServer">
<include name="moparclassic.jar" />
</fileset>
<fileset id="common-libraries" dir="${common-lib}">
<include name="*.jar" />
</fileset>
<fileset id="production-classes" dir="${bin}">
<include name="**/*.class" />
</fileset>
<path id="binary-path">
<pathelement path="${bin}" />
</path>
<path id="library-path">
<fileset refid="common-libraries" />
<fileset refid="mopar" />
</path>
<path id="master-path">
<path refid="binary-path" />
<path refid="library-path" />
</path>
<target name="init">
<mkdir dir="${bin}" />
</target>
<target name="build" depends="init">
<javac destdir="${bin}" includeantruntime="false">
<src path="${src}" />
<classpath refid="library-path" />
</javac>
<jar destfile="${jar}">
<fileset refid="production-classes" />
</jar>
<delete dir="${bin}"/>
</target>
<target name="clean">
<delete dir="${bin}" />
<delete file="${jar}" />
</target>
</project>

View File

@ -0,0 +1,63 @@
package org.moparscape.msc.gs.db.impl
import org.moparscape.msc.gs.db.DataService
import scala.collection.mutable.ListBuffer
import java.util.List
import collection.JavaConversions._
import org.moparscape.msc.gs.model.World
import java.sql.PreparedStatement
import java.sql.SQLException
import org.moparscape.msc.gs.util.Logger
class MySQLDataService protected() extends DataService {
private val conn = new DBConnection
override def banIP(ip: String) = {
var ret = false
try {
block.setString(1, ip)
block.executeUpdate
block.close
ret = true
} catch {
case e: SQLException => {
if (!e.getMessage.startsWith("Duplicate entry")) {
ret = false
}
}
case e => {
Logger.error(e)
ret = false
}
}
ret
}
override def unbanIP(ip: String) {
try {
unblock.setString(1, ip)
unblock.executeUpdate
unblock.close
} catch {
case _ =>
}
}
override def requestIPBans: List[String] = {
val query = "SELECT `ip` from `pk_ipbans`"
val result = conn.getQuery(query)
val list = new ListBuffer[String]
while (result.next) {
list += result.getString("ip")
}
list.toList
}
val block: PreparedStatement = {
conn.getConnection.prepareStatement("INSERT INTO `pk_ipbans` (`ip`) VALUES(?)")
}
val unblock: PreparedStatement = {
conn.getConnection.prepareStatement("DELETE FROM `pk_ipbans` WHERE ip = ?")
}
}

View File

@ -1,16 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="DataStore Core" default="build" basedir="../../">
<property name="base" location="Modules/DataStore" />
<project name="NIO Data Service" default="build" basedir="../../../">
<property name="name" value="NIODataService" />
<property name="package" value="DataService" />
<property name="base" location="Modules/${package}/${name}" />
<property name="src" location="${base}/src" />
<property name="bin" location="${base}/bin" />
<property name="lib" location="${base}/lib" />
<property name="jar" value="${base}/DataStoreCore.jar" />
<property name="common-lib" location="${base}/../MySQLCommon" />
<property name="jar" value="${base}/${name}.jar" />
<fileset id="mopar" dir="GameServer">
<include name="moparclassic.jar" />
</fileset>
<fileset id="libraries" dir="${lib}">
<fileset id="common-libraries" dir="${common-lib}">
<include name="*.jar" />
</fileset>
@ -23,7 +25,7 @@
</path>
<path id="library-path">
<fileset refid="libraries" />
<fileset refid="common-libraries" />
<fileset refid="mopar" />
</path>
@ -34,7 +36,6 @@
<target name="init">
<mkdir dir="${bin}" />
<mkdir dir="${lib}" />
</target>
<target name="build" depends="init">
@ -43,9 +44,9 @@
<classpath refid="library-path" />
</javac>
<jar destfile="${jar}">
<zipgroupfileset refid="libraries" />
<fileset refid="production-classes" />
</jar>
<delete dir="${bin}"/>
</target>
<target name="clean">

View File

@ -1,4 +1,4 @@
package org.moparscape.msc.gs.db;
package org.moparscape.msc.gs.db.impl;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@ -6,6 +6,7 @@ import java.util.Iterator;
import org.moparscape.msc.gs.Instance;
import org.moparscape.msc.gs.core.GameEngine;
import org.moparscape.msc.gs.db.ReportHandler;
import org.moparscape.msc.gs.model.Player;
import org.moparscape.msc.gs.model.World;
import org.moparscape.msc.gs.model.snapshot.Activity;
@ -13,7 +14,11 @@ import org.moparscape.msc.gs.model.snapshot.Chatlog;
import org.moparscape.msc.gs.model.snapshot.Snapshot;
import org.moparscape.msc.gs.util.Logger;
public class ReportHandlerQueries {
class MySQLReportHandler implements ReportHandler {
MySQLReportHandler() {
}
/**
* Inserts a new row into "msc2_reports" table
*/
@ -53,6 +58,7 @@ public class ReportHandlerQueries {
* @param reason
* What type of a report is this
*/
@Override
public synchronized void submitReport(long from, long about, byte reason,
Player from2) {
@ -116,6 +122,7 @@ public class ReportHandlerQueries {
}
}
@Override
public synchronized void submitDupeData(String username, Long hash) {
StringBuilder data = new StringBuilder();
Iterator<Snapshot> i = Instance.getWorld().getSnapshots()

Binary file not shown.

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="NIO Data Service" default="build" basedir="../../../">
<property name="name" value="NIODataService" />
<property name="package" value="DataService" />
<property name="base" location="Modules/${package}/${name}" />
<property name="src" location="${base}/src" />
<property name="bin" location="${base}/bin" />
<property name="jar" value="${base}/${name}.jar" />
<fileset id="mopar" dir="GameServer">
<include name="moparclassic.jar" />
</fileset>
<fileset id="production-classes" dir="${bin}">
<include name="**/*.class" />
</fileset>
<path id="binary-path">
<pathelement path="${bin}" />
</path>
<path id="library-path">
<fileset refid="mopar" />
</path>
<path id="master-path">
<path refid="binary-path" />
<path refid="library-path" />
</path>
<target name="init">
<mkdir dir="${bin}" />
</target>
<target name="build" depends="init">
<javac destdir="${bin}" includeantruntime="false">
<src path="${src}" />
<classpath refid="library-path" />
</javac>
<jar destfile="${jar}">
<fileset refid="production-classes" />
</jar>
<delete dir="${bin}"/>
</target>
<target name="clean">
<delete dir="${bin}" />
<delete file="${jar}" />
</target>
</project>

View File

@ -0,0 +1,139 @@
package org.moparscape.msc.gs.db.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import org.moparscape.msc.gs.db.DataService;
public class NIODataService implements DataService {
NIODataService() {
}
private static final File data = new File("ip-bans.txt");
private static final ArrayList<String> ipBans = getIPBans();
@SuppressWarnings("unchecked")
@Override
public List<String> requestIPBans() {
return (List<String>) ipBans.clone();
}
private static ArrayList<String> getIPBans() {
ArrayList<String> d = new ArrayList<String>();
if (!data.exists()) {
return d;
}
FileInputStream fin = null;
FileChannel chan = null;
ByteBuffer buf = null;
try {
fin = new FileInputStream(data.getPath());
chan = fin.getChannel();
long size = chan.size();
buf = ByteBuffer.allocateDirect((int) size);
chan.read(buf);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fin.close();
chan.close();
} catch (IOException e) {
}
}
buf.rewind();
StringBuilder sb = new StringBuilder(15);
for (int i = 0; i < buf.capacity(); i++) {
char c = (char) buf.get();
if (c == '\r') {
continue;
}
if (c == '\n') {
d.add(sb.toString());
sb = new StringBuilder(15);
continue;
}
sb.append(c);
}
return d;
}
@Override
public void unbanIP(String ip) {
synchronized (ipBans) {
ipBans.remove(ip);
}
save();
}
private void save() {
List<String> ipBans = requestIPBans();
if (ipBans.isEmpty()) {
data.delete();
}
StringBuilder sb = new StringBuilder(16 * ipBans.size());
for (String ip : ipBans) {
sb.append(ip).append('\n');
}
String d = sb.toString();
ByteBuffer buf = ByteBuffer.allocateDirect(d.length());
for (char c : d.toCharArray()) {
buf.put((byte) c);
}
buf.flip();
if (!data.exists()) {
try {
data.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fos = null;
FileChannel chan = null;
try {
fos = new FileOutputStream(data);
chan = fos.getChannel();
chan.write(buf);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
chan.close();
fos.close();
} catch (IOException e) {
}
}
}
@Override
public boolean banIP(String ip) {
synchronized (ipBans) {
if (!ipBans.contains(ip)) {
ipBans.add(ip);
}
}
save();
return true;
}
}

Binary file not shown.

View File

@ -1,11 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="XML Using XStream" default="build" basedir="../../../">
<property name="base" location="Modules/DataStore/XMLUsingXStream" />
<property name="name" value="XMLUsingXStream" />
<property name="package" value="DataStore" />
<property name="base" location="Modules/${package}/${name}" />
<property name="src" location="${base}/src" />
<property name="bin" location="${base}/bin" />
<property name="lib" location="${base}/lib" />
<property name="common-lib" location="${base}/../lib" />
<property name="jar" value="${base}/XMLUsingXStreamDataStore.jar" />
<property name="jar" value="${base}/${name}.jar" />
<fileset id="mopar" dir="GameServer">
<include name="moparclassic.jar" />
@ -19,10 +21,6 @@
<include name="*.jar" />
</fileset>
<fileset id="datastore-core" dir="${base}/../">
<include name="DataStoreCore.jar" />
</fileset>
<fileset id="production-classes" dir="${bin}">
<include name="**/*.class" />
</fileset>
@ -35,7 +33,6 @@
<fileset refid="common-libraries" />
<fileset refid="libraries" />
<fileset refid="mopar" />
<fileset refid="datastore-core" />
</path>
<path id="master-path">