add MySqlHelper...

Signed-off-by: 502647092 <jtb1@163.com>
master
502647092 2015-08-18 20:35:32 +08:00
parent af41dcd7b9
commit a42ef6a78b
9 changed files with 503 additions and 34 deletions

View File

@ -1,5 +1,7 @@
package cn.citycraft.CTZLoginServer;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
@ -9,10 +11,17 @@ import org.bukkit.plugin.java.JavaPlugin;
import cn.citycraft.CTZLoginServer.Socket.CTZLoginServerSocket;
import cn.citycraft.CTZLoginServer.config.Config;
import cn.citycraft.CTZLoginServer.listen.PlayerListen;
import cn.citycraft.CTZLoginServer.utils.MySqlHelper;
public class CTZLoginServer extends JavaPlugin {
public String version;
public ServerMode servermode;
public CTZLoginServerSocket serversocket;
public static MySqlHelper mysql = null;
enum ServerMode {
Main, Obey
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
@ -37,7 +46,42 @@ public class CTZLoginServer extends JavaPlugin {
pm.disablePlugin(this);
return;
}
this.onLoadLoginServer();
if (servermode == ServerMode.Main) {
getLogger().info("主模式启动服务器...");
this.onLoadLoginServer();
} else {
getLogger().info("子模式启动监听器...");
}
if (Config.getInstance().getBoolean("config.mysql.enable")) {
this.getLogger().info("已启用MySQL保存数据,开始连接数据库...");
// 连接数据库用到的一些参数.
String dbHost = Config.getMessage("config.mysql.ip");
String dbPort = Config.getMessage("config.mysql.port");
String dbName = Config.getMessage("config.mysql.database");
String dbuserName = Config.getMessage("config.mysql.username");
String dbpwd = Config.getMessage("config.mysql.password");
String dbtable = Config.getMessage("config.mysql.tablename");
mysql = new MySqlHelper(dbHost, dbPort, dbName, dbuserName, dbpwd);
if (mysql.dbConnection()) {
this.getLogger().info("数据库连接成功,检查数据表是否存在...");
if (!mysql.isTableExists(dbtable)) {
this.getLogger().info("数据表不存在,新建表" + dbtable + "...");
HashMap<String, String> fields = new HashMap<String, String>();
fields.put("player", "VARCHAR(255) NOT NULL");
fields.put("ip", "NOT NULL DEFAULT '127.0.0.1'");
fields.put("islogged", "SMALLINT(6) NOT NULL DEFAULT '0'");
String Conditions = "UNIQUE (`player`)";
if (!mysql.createTables(dbtable, fields, Conditions)) {
this.getLogger().info("数据表" + dbtable + "创建失败,请尝试手动创建并重启服务器...");
}
}
} else {
this.getLogger().warning("数据库连接失败!");
pm.disablePlugin(this);
return;
}
}
pm.registerEvents(new PlayerListen(), this);
getLogger().info("CTZLoginServer已加载!");
}
@ -46,6 +90,10 @@ public class CTZLoginServer extends JavaPlugin {
public void onLoad() {
Config.load(this, "1.0");
CTZServers.Init(Config.getInstance().getConfigurationSection("areas"));
if (Config.getMessage("config.mode").equalsIgnoreCase("main"))
servermode = ServerMode.Main;
else
servermode = ServerMode.Obey;
}
public void onLoadLoginServer() {
@ -53,8 +101,7 @@ public class CTZLoginServer extends JavaPlugin {
serversocket.ShutDown();
getLogger().info("CTZL登录服务器已关闭!");
}
serversocket = new CTZLoginServerSocket(this, Config.getInstance().getInt("config.port",
25580));
serversocket = new CTZLoginServerSocket(this, Config.getInstance().getInt("config.port", 25580));
this.getServer().getScheduler().runTaskAsynchronously(this, serversocket);
getLogger().info("CTZL登录服务器已开启!");
}

View File

@ -12,7 +12,13 @@ import org.bukkit.configuration.ConfigurationSection;
import com.google.gson.Gson;
class Area {
/**
*
*/
String name;
/**
*
*/
List<Server> servers = new ArrayList<Server>();
public String getName() {
@ -33,6 +39,9 @@ class Area {
}
class CTZServer {
/**
*
*/
List<Area> areas = new ArrayList<Area>();
public List<Area> getAreas() {
@ -53,11 +62,21 @@ public class CTZServers {
static CTZServer sl = new CTZServer();
/**
* json
*
* @return
*/
public static String getJson() {
Gson gson = new Gson();
return chinaToUnicode(gson.toJson(sl));
}
/**
*
*
* @param
*/
public static void Init(ConfigurationSection cs) {
Set<String> arealist = cs.getKeys(false);
for (String a : arealist) {
@ -126,18 +145,39 @@ public class CTZServers {
*/
class Server {
/**
*
*/
public String name;
/**
*
*/
public String address;
/**
*
*/
public int port;
/**
*
*/
public String info;
/**
*
*/
public String version;
/**
*
*/
public String url;
/**
*
*/
public String depend;
public String getDepend() {

View File

@ -2,7 +2,6 @@ package cn.citycraft.CTZLoginServer.Socket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
@ -34,8 +33,7 @@ public class CTZLoginServerSocket implements Runnable {
// 用于接收客户端发来的请求
br = new BufferedReader(new InputStreamReader(client.getInputStream()));
// 用于发送返回信息,可以不需要装饰这么多io流使用缓冲流时发送数据要注意调用.flush()方法
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
client.getOutputStream())), true);
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
ip = client.getInetAddress().getHostAddress();
while (true) {
String str = br.readLine();
@ -67,8 +65,7 @@ public class CTZLoginServerSocket implements Runnable {
}
if (API.registerPlayer(username, password)) {
res.setHtml("true");
Bukkit.getConsoleSender().sendMessage(
"§6玩家: §a" + username + " §d注册成功 IP: " + ip);
Bukkit.getConsoleSender().sendMessage("§6玩家: §a" + username + " §d注册成功 IP: " + ip);
} else {
res.setHtml("false");
}
@ -87,8 +84,7 @@ public class CTZLoginServerSocket implements Runnable {
} else {
CTZLoginQueue.add(username);
}
Bukkit.getConsoleSender().sendMessage(
"§6玩家: §a" + username + " §3登录成功 IP: " + ip);
Bukkit.getConsoleSender().sendMessage("§6玩家: §a" + username + " §3登录成功 IP: " + ip);
} else {
res.setHtml("false");
}
@ -182,7 +178,7 @@ public class CTZLoginServerSocket implements Runnable {
try {
socket.close();
s.close();
} catch (IOException e) {
} catch (Exception e) {
System.out.println("CTZL服务器已关闭...");
}
}

View File

@ -1,16 +1,30 @@
package cn.citycraft.CTZLoginServer.config;
import java.io.File;
import java.io.IOException;
import org.bukkit.plugin.Plugin;
public class Config extends ConfigLoader {
private static String CONFIG_NAME = "config.yml";
private static FileConfig instance;
private static File file;
public Config(Plugin p) {
super(p, CONFIG_NAME);
file = new File(p.getDataFolder(), CONFIG_NAME);
instance = super.getInstance();
}
public Config(Plugin p, String ver) {
super(p, CONFIG_NAME, ver);
instance = super.getInstance();
}
public static void load(Plugin p) {
new Config(p);
}
public static void load(Plugin p, String ver) {
new Config(p, ver);
}
@ -20,11 +34,22 @@ public class Config extends ConfigLoader {
}
public static String getMessage(String path) {
String message = instance.getString(path).replaceAll("&", "§");
String message = instance.getString(path);
if (message != null)
message = message.replaceAll("&", "§");
return message;
}
public static String[] getStringArray(String path) {
return instance.getStringList(path).toArray(new String[0]);
}
public static void save() {
try {
instance.save(file);
} catch (IOException e) {
saveError(file);
e.printStackTrace();
}
}
}

View File

@ -32,8 +32,7 @@ public class ConfigLoader extends FileConfig {
public ConfigLoader(Plugin p, String filename) {
ConfigLoader.plugin = p;
config = loadConfig(p, new File(p.getDataFolder(), filename), null,
true);
config = loadConfig(p, new File(p.getDataFolder(), filename), null, true);
}
public ConfigLoader(Plugin p, String filename, boolean res) {
@ -56,7 +55,7 @@ public class ConfigLoader extends FileConfig {
}
public FileConfig loadConfig(Plugin p, File file, String ver, boolean res) {
tip = res ;
tip = res;
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
p.getLogger().info("创建新的文件夹" + file.getParentFile().getAbsolutePath() + "...");
@ -68,16 +67,23 @@ public class ConfigLoader extends FileConfig {
FileConfig configcheck = init(file);
String version = configcheck.getString("version");
if (version == null || !version.equals(ver)) {
p.getLogger().warning("配置文件: " + file.getName() + " 版本过低 正在升级...");
try {
configcheck.save(new File(file.getParent(), file.getName() + ".backup"));
p.getLogger()
.warning(
"配置文件: " + file.getName() + " 已备份为 " + file.getName()
+ ".backup !");
} catch (IOException e) {
p.getLogger().warning("配置文件: " + file.getName() + "备份失败!");
}
p.saveResource(file.getName(), true);
p.getLogger().warning(
"配置文件: " + file.getName() + " 版本过低 正在升级...");
p.getLogger().info("配置文件: " + file.getName() + "升级成功!");
}
}
}
if (tip)
p.getLogger().info(
"载入配置文件: " + file.getName()
+ (ver != null ? " 版本: " + ver : ""));
p.getLogger().info("载入配置文件: " + file.getName() + (ver != null ? " 版本: " + ver : ""));
return init(file);
}

View File

@ -27,8 +27,8 @@ import com.google.common.base.Charsets;
import com.google.common.io.Files;
/**
* An implementation of {@link Configuration} which saves all files in Yaml.
* Note that this implementation is not synchronized.
* An implementation of {@link Configuration} which saves all files in Yaml. Note that this
* implementation is not synchronized.
*/
public class FileConfig extends YamlConfiguration {
@ -51,13 +51,13 @@ public class FileConfig extends YamlConfiguration {
}
protected final DumperOptions yamlOptions = new DumperOptions();
protected final Representer yamlRepresenter = new YamlRepresenter();
protected final Yaml yaml = new Yaml(new YamlConstructor(),
yamlRepresenter, yamlOptions);
protected final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);
@Override
public void load(File file) throws FileNotFoundException, IOException,
InvalidConfigurationException {
public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException {
Validate.notNull(file, "File cannot be null");
final FileInputStream stream = new FileInputStream(file);
load(new InputStreamReader(stream, Charsets.UTF_8));
@ -85,8 +85,7 @@ public class FileConfig extends YamlConfiguration {
Validate.notNull(file, "File cannot be null");
Files.createParentDirs(file);
String data = saveToString();
Writer writer = new OutputStreamWriter(new FileOutputStream(file),
Charsets.UTF_8);
Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8);
try {
writer.write(data);
} finally {

View File

@ -0,0 +1,340 @@
package cn.citycraft.CTZLoginServer.utils;
/*
*
*/
// import java.sql.*;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author
* 20157143:25:06
*
*/
public class MySqlHelper {
// ///////////////////////////////////////———–>>>数据成员 and 构造函数
private Connection dbconn;
private Statement dbstate;
private ResultSet dbresult;
protected String username;
protected String password;
protected String url;
private String driverName = "com.mysql.jdbc.Driver";
public MySqlHelper() {
dbconn = null;
dbstate = null;
dbresult = null;
}
public void print(String str)// 简化输出
{
System.out.println(str);
}
/**
* MySql
*
* @param host
* @param port
* @param dbaName
* @param usName
* @param psw
* @return bool
*/
public MySqlHelper(String host, String port, String dbaName, String usName, String password) {
try {
Class.forName(driverName).newInstance();
} catch (Exception e) {
}// "org.gjt.mm.mysql.Driver"两个驱动都可以用
String dbHost = host;// 数据库的一些信息
String dbPort = port;
String dbName = dbaName;
String Encode = "?&useUnicode=true&characterEncoding=utf-8"; // 解决MySql中文问题,要连续写不能空格
this.username = usName;
this.password = password;
this.url = "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName + Encode;
}// end boolean dbConnection(…)
public boolean dbConnection() {
try {
dbconn = DriverManager.getConnection(url, username, password);
return true;
} catch (Exception e) {
print("数据库操作出错: " + e.getMessage());// 得到出错信息
print("登录URL: " + url); // 发生错误时,将连接数据库信息打印出来
print("登录账户: " + username);
print("登录密码: " + password);
return false;
}
}
public boolean isTableExists(final String table) {
try {
dbConnection();
final DatabaseMetaData dbm = dbconn.getMetaData();
final ResultSet tables = dbm.getTables(null, null, table, null);
return tables.next();
} catch (final SQLException e) {
e.printStackTrace();
}
return false;
}
public boolean createTables(String tableName, HashMap<String, String> fields, String Conditions) {
dbConnection();
String kv = "";
for (Entry<String, String> kvs : fields.entrySet()) {
kv += "`" + kvs.getKey() + "` " + kvs.getValue() + ", ";
}
if (kv.length() == 0)
return false;
kv = kv.substring(0, kv.length() - 2);// 根据String的索引提取子串
String sql = "CREATE TABLE `" + tableName + "` ( " + kv + (Conditions == "" ? "" : " , " + Conditions)
+ " ) ENGINE = InnoDB DEFAULT CHARSET=UTF8";
try {
PreparedStatement state = dbconn.prepareStatement(sql);
state.executeUpdate();
state.close();
return true;
} catch (final Exception e) {
print("数据库操作出错: " + e.getMessage());
print("SQL查询语句: " + sql);
}
return false;
}
/**
* !
*
* @param tableName
*
* @param fieles
*
* @param selCondition
*
* @return
*/
public boolean dbExist(String tableName, HashMap<String, String> selConditions) {
dbConnection();
String selCondition = "";
if (selConditions != null && !selConditions.isEmpty()) {
for (Entry<String, String> kvs : selConditions.entrySet()) {
selCondition += kvs.getKey() + "='" + kvs.getValue() + "', ";
}
selCondition = " WHERE " + selCondition.substring(0, selCondition.length() - 2);// 根据String的索引提取子串
}
String sql = "SELECT * FROM " + tableName + selCondition;
try {
dbstate = dbconn.createStatement();
dbresult = dbstate.executeQuery(sql);
return dbresult.next();
} catch (Exception e) {
print("数据库操作出错: " + e.getMessage());
print("SQL查询语句: " + sql);
}
return false;
}
/**
*
*
* @param tableName
*
* @param fieles
*
* @param selCondition
*
* @return
*/
public String dbSelectFirst(String tableName, String fields, HashMap<String, String> selConditions) {
dbConnection();
String selFieldsTem = fields;
String selCondition = "";
if (selConditions != null && !selConditions.isEmpty()) {
for (Entry<String, String> kvs : selConditions.entrySet()) {
selCondition += kvs.getKey() + "='" + kvs.getValue() + "', ";
}
selCondition = " WHERE " + selCondition.substring(0, selCondition.length() - 2);// 根据String的索引提取子串
}
String sql = "SELECT " + selFieldsTem + " FROM " + tableName + selCondition + " limit 1";
try {
dbstate = dbconn.createStatement();
dbresult = dbstate.executeQuery(sql);
if (dbresult.next()) {
return dbresult.getString(fields);
}
} catch (Exception e) {
print("数据库操作出错: " + e.getMessage());
print("SQL查询语句: " + sql);
}
return null;
}
/**
*
*
* @param tableName
*
* @param fieles
*
* @param selCondition
*
* @return mapList
*/
@SuppressWarnings({
"rawtypes",
"unchecked"
})
public List dbSelect(String tableName, List<String> fields, String selCondition) {
dbConnection();
List mapInList = new ArrayList();
String selFields = "";
for (int i = 0; i < fields.size(); ++i)
selFields += fields.get(i) + ", ";
String selFieldsTem = selFields.substring(0, selFields.length() - 2);// 根据String的索引提取子串
String sql = "SELECT " + selFieldsTem + " FROM `" + tableName + "`" + selCondition == "" ? "" : " WHERE " + selCondition;
try {
dbstate = dbconn.createStatement();
try {
dbresult = dbstate.executeQuery(sql);
} catch (Exception e) {
print("数据库操作出错: " + e.getMessage());
print("SQL查询语句: " + sql);
}
while (dbresult.next()) {
Map selResult = new HashMap();
for (String col : fields) {
selResult.put(col, dbresult.getString(col));
}
mapInList.add(selResult);
}
} catch (Exception e) {
print("数据库操作出错: " + e.getMessage());
print("SQL查询语句: " + sql);
}
return mapInList;
}// end String dbSelect(…)
/**
*
*
* @param tableName
* @param condition
* @return bool
*/
public boolean dbDelete(String tableName, HashMap<String, String> selConditions) {// ——–>>>删除操作
dbConnection();
String selCondition = "";
if (selConditions != null && !selConditions.isEmpty()) {
for (Entry<String, String> kvs : selConditions.entrySet()) {
selCondition += kvs.getKey() + "='" + kvs.getValue() + "', ";
}
selCondition = " WHERE " + selCondition.substring(0, selCondition.length() - 2);// 根据String的索引提取子串
}
String sql = "DELETE FROM `" + tableName + "` " + selCondition;
try {
dbstate.executeUpdate(sql);
return true;
} catch (Exception e) {
print("数据库操作出错: " + e.getMessage());
print("SQL查询语句: " + sql);
return false;
}
}// end dbDelete(…)
/**
*
*
* @param tabName
* @param reCount
* @return booltruefalse
*/
@SuppressWarnings({
"rawtypes"
})
public boolean dbUpdate(String tabName, HashMap reCount, String upCondition) {
dbConnection();
String Values = "";
Iterator keyValues = reCount.entrySet().iterator();
for (int i = 0; i < reCount.size(); ++i) {
Map.Entry entry = (Map.Entry) keyValues.next();
Object key = entry.getKey();
Object value = entry.getValue();
Values += key + "='" + value + "'" + ", ";
}
String updateValues = Values.substring(0, Values.length() - 2);
String sql = "UPDATE `" + tabName + "` SET " + updateValues + " " + upCondition;
try {
dbstate.executeUpdate(sql);
return true;
} catch (Exception e) {
print("数据库操作出错: " + e.getMessage());
print("SQL查询语句: " + sql);
return false;
}
}// end dbUpdate(…)
/**
*
*
* @param tabName
* -
* @param values
* - HashMap
* @return booltruefalse
*/
public boolean dbInsert(String tabName, HashMap<String, String> values) {
dbConnection();
String sql = "";
String insertFields = "";
String insertValues = "";
for (Entry<String, String> kvs : values.entrySet()) {
insertFields += "`" + kvs.getKey() + "`, ";
insertValues += "'" + kvs.getValue() + "', ";
}
insertFields = insertFields.substring(0, insertFields.length() - 2);
insertValues = insertValues.substring(0, insertValues.length() - 2);
sql += "INSERT INTO `" + tabName + "` (" + insertFields + ") VALUES" + "(" + insertValues + ")";
try {
dbstate.executeUpdate(sql);
return true;
} catch (Exception e) {
print("数据库操作出错: " + e.getMessage());
print("SQL查询语句: " + sql);
return false;
}
}// end dbInsert(…)
/**
*
*
* @return booltruefalse
*/
public boolean dbClose() {
try {
dbconn.close();
return true;
} catch (Exception e) {
print("数据库操作出错: " + e.getMessage());
return false;
}
}// end dbClose()
}

View File

@ -8,12 +8,28 @@ pluginname: '&6[&bCTZL&6]&r'
tipplayer: true
#服务器配置
config:
#服务器模式[main(主服模式)|obey(子服模式)]
mode: main
#服务器监听端口
port: 25580
#断线重连超时
timeout: 10
#强制使用专用客户端(关闭则可以同时使用自带登录和外部登录)
forceclient: true
mysql:
enable: true
#数据库需要自行建立
database: minecraft
#数据表
tablename: ctzloginserver
#用户名
username: root
#密码
password:
#地址
ip: localhost
#端口
port: 3306
areas:
1:
name: '纯净大区'
@ -21,18 +37,18 @@ areas:
1:
name: "InfinityZone"
address: "four.mengcraft.com"
port: 25565
port: 11133
info: "InfinityZone \u000d 稳定 声誉 生存 地皮 小游戏"
depend: "1.8"
version: "1.8-Forge"
url: "CityCraft.cn"
url: "four.mengcraft.com"
2:
name: '模组大区'
servers:
1:
name: "光小镇"
name: "光小镇"
address: "CityCraft.cn"
port: 25573
port: 25565
info: "MOD服务器: 豆腐 家具 "
depend: ""
version: "1.7.10-Forge"

View File

@ -1,7 +1,7 @@
name: CTZLoginServer
main: cn.citycraft.CTZLoginServer.CTZLoginServer
version: 0.0.1
depend: [AuthMe]
version: 1.0
softdepend: [AuthMe]
commands:
ctzl:
description: CTZLoginServer Reload.