订阅本站
package com.loojoy.supmarket.rules;
import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
 import org.apache.log4j.PropertyConfigurator;
 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;
 import org.springframework.web.servlet.ModelAndView;
 import org.springframework.web.servlet.mvc.Controller;
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
import com.google.code.facebookapi.FacebookException;
 import com.google.code.facebookapi.FacebookXmlRestClient;
 import com.google.code.facebookapi.ProfileField;
 import com.loojoy.supmarket.common.FBConnector;
 import com.loojoy.supmarket.common.FlashWritter;
 import com.loojoy.supmarket.model.GamePlayer;
 import com.loojoy.supmarket.model.Shopkeepper;
 import com.loojoy.supmarket.persisetence.bean.Account;
 import com.loojoy.supmarket.persisetence.bean.Backpack;
 import com.loojoy.supmarket.persisetence.bean.EmployeeFashion;
 import com.loojoy.supmarket.persisetence.bean.Employees;
 import com.loojoy.supmarket.persisetence.bean.Houseinside;
 import com.loojoy.supmarket.persisetence.bean.Market;
 import com.loojoy.supmarket.persisetence.dao.AccountDao;
 import com.loojoy.supmarket.persisetence.dao.BackPackDao;
 import com.loojoy.supmarket.persisetence.dao.EmployeeFashionDao;
 import com.loojoy.supmarket.persisetence.dao.EmployeesDao;
 import com.loojoy.supmarket.persisetence.dao.HouseInSideDao;
 import com.loojoy.supmarket.persisetence.dao.MailDao;
 import com.loojoy.supmarket.persisetence.dao.MarketDao;
 import com.loojoy.supmarket.rules.operater.ArticleOper;
 import com.loojoy.supmarket.rules.operater.HouseInSideOper;
 import com.loojoy.supmarket.rules.operater.HouseOutSideOper;
 import com.loojoy.supmarket.rules.operater.InitMarketMess;
 import com.loojoy.supmarket.rules.operater.MailOper;
 import com.loojoy.supmarket.rules.operater.UserChangeFashionOper;
 import com.loojoy.supmarket.utils.PathUtil;
/**
 * 用户登陆<br>
 *
 * <p>
 * 创建角色的相关实例,并将信息返回到客户端<br>
 *
 * @author estone
 */
 public class LoginController implements Controller {
/**
 * 处理角色请求信息
 */
 public ModelAndView handleRequest(HttpServletRequest request,
 HttpServletResponse response) throws Exception {
 request.setCharacterEncoding("utf-8");
 response.setCharacterEncoding("utf-8");
// Facebook客户端
 Object request_obj = FBConnector.connectFacebook(request, response);
if (request_obj instanceof FacebookXmlRestClient) {
 FacebookXmlRestClient client = (FacebookXmlRestClient) request_obj;
 logger.info(" 登陆的客户端信息 : " + client);
// 角色登陆
 if (client != null) {
 long uid = client.users_getLoggedInUser();
System.out.println(" 当前登陆的角色uid为: " + uid);
 boolean isAddApp = new AccountDao().queryUserIsAddApps(uid);
 System.out.println(" 当前登陆的角色isAddApp为: " + isAddApp);
// 用户第一次登陆
 if (!isAddApp) {
 GamePlayer gamePlayer = this.initGamePlayer(client);
 JSONObject firstLoginMsg = this.firstLoginMsg(gamePlayer);
 request.setAttribute("initData", firstLoginMsg.toString());
 return new ModelAndView("./game/init.jsp");
 }
ModelAndView model_view = this.sendInitClientMessage(uid,
 request, response, client);
 System.out.println(" 返回的模型视图的名称为 " + model_view);
 logger.info(" 返回的模型视图的名称为 " + model_view);
return model_view;
 }
 // 请求参数错误
 else {
 throw new IllegalArgumentException(
 "ERROR: 404,request unaviliable");
 }
 }
 // 角色的其他交互信息
 else {
 this.processGameRules(request, response);
 return null;
 }
 }
/**
 * 角色第一次登陆时使用的信息
 *
 * @throws JSONException
 */
 public JSONObject firstLoginMsg(GamePlayer gamePlayer) throws JSONException {
 JSONObject gamePlayerMsg = new JSONObject(gamePlayer
 .getObjectParamters());
 JSONObject firstLogin = new JSONObject();
 firstLogin.put("event", "init");
 firstLogin.put("roleInfo", gamePlayerMsg);
 firstLogin.put("employee", "");
 firstLogin.put("mail", "");// 添加邮件信息
 return firstLogin;
 }
/**
 * 游戏逻辑
 */
 public void processGameRules(HttpServletRequest request,
 HttpServletResponse response) {
 String requestMessage = request.getParameter("json");
 logger.info(" 接收到的客户端协议为 :" + requestMessage);
if (requestMessage == null || requestMessage == "")
 throw new IllegalArgumentException("ERROR: 404,request unaviliable");
try {
 JSONObject json = new JSONObject(requestMessage);
 String event = (String) json.get("event");
 System.out.println(" 接收到的客户端的事件为 " + event);
// 雇佣好友
 if (event.equalsIgnoreCase("getFriends")) {
 long roleId = json.getLong("roleID");
 JSONObject event_msg = this.getFriendList(roleId);
 logger.info("客户端的地址 :  " + request.getRemoteHost());
 FlashWritter.writeMessage(response, event_msg.toString());
 }
 // 人物换装
 else if (event.equals("setFashion")) {
 JSONObject setFashion = new UserChangeFashionOper()
 .userChangeFashion(json);
 FlashWritter.writeMessage(response, setFashion.toString());
}
 // 部门分配
 else if (event.equals("departManager")) {
 this.departmentPosition(request, response, json);
 } // 请求邮件
 else if (event.equals("mail")) {
 JSONObject gameMail = new MailOper().getMailList(2);
 FlashWritter.writeMessage(response, gameMail.toString());
 }
 // 删除邮件
 else if (event.equals("deleteMail")) {
 JSONObject deleteMail = new MailOper().deleteMail(json);
 FlashWritter.writeMessage(response, deleteMail.toString());
 }
 // 写邮件
 else if (event.equals("writeMail")) {
 JSONObject writeMail = new MailOper().writeMail(json);
 FlashWritter.writeMessage(response, writeMail.toString());
 }
 // 读邮件
 else if (event.equals("readMail")) {
 JSONObject readMail = new MailOper().readMail(json);
 FlashWritter.writeMessage(response, readMail.toString());
 }// 外场景信息
 else if (event.equals("houseOutside")) {
 JSONObject outside = new HouseOutSideOper().houseOutOper(json);
 FlashWritter.writeMessage(response, outside.toString());
 }// 内场景信息
 else if (event.equals("houseInside")) {
 JSONObject inside = new HouseInSideOper().houseInOper(json);
 FlashWritter.writeMessage(response, inside.toString());
 } else if (event.equals("outStreet")) {
 JSONObject outStreet = new InitMarketMess().getOutStreet();
 FlashWritter.writeMessage(response, outStreet.toString());
 }// 外场景背包
 else if (event.equals("OutStreetBag")) {
 JSONObject article = new ArticleOper().getArticle(json);
 FlashWritter.writeMessage(response, article.toString());
 }
} catch (Exception ex) {
 ex.printStackTrace();
 }
 }
public JSONObject getFriendList(Long roleId) throws FacebookException,
 JSONException {
 FacebookXmlRestClient client = OnlineMap.getPlayer(roleId).getClient();
 Document doc = client.friends_get();
NodeList userIDNodes = doc.getElementsByTagName("uid");
 List<Long> friends = new ArrayList<Long>();
 JSONArray jsonArray = new JSONArray();
if (userIDNodes.getLength() < 5) {
 for (int i = 0; i < userIDNodes.getLength(); i++) {
 JSONObject friend = this.getFriendInfor(userIDNodes, friends,
 client, i);
 jsonArray.put(friend);
 }
 }
 // 好友的数量小于5
 else {
 for (int i = 0; i <= 5; i++) {
 JSONObject friend = this.getFriendInfor(userIDNodes, friends,
 client, i);
 jsonArray.put(friend);
 }
 }
 JSONObject event_msg = new JSONObject();
 event_msg.put("event", "getFriends");
 event_msg.put("success", true);
 event_msg.put("friends", jsonArray);
System.out.println("好友的基本信息为" + event_msg.toString());
 return event_msg;
 }
public JSONObject getFriendInfor(NodeList userIDNodes, List<Long> friends,
 FacebookXmlRestClient client, int i) throws FacebookException,
 JSONException {
 Node node = userIDNodes.item(i);
 String idText = node.getTextContent();
 Long id = Long.valueOf(idText);
 friends.add(id);
 System.out.println("第 " + i + " 位好友ID  : " + idText);
 Document tmp_doc = client
 .fql_query("SELECT first_name , pic FROM user WHERE uid=" + id);
 NodeList usr_list = tmp_doc.getElementsByTagName("user");
 Node node_usr = usr_list.item(0);
 NodeList child_nodes = node_usr.getChildNodes();
 String user_name = null;
 String pic_url = null;
if (child_nodes.getLength() >= 1) {
 user_name = child_nodes.item(0).getTextContent();
 pic_url = child_nodes.item(1).getTextContent();
 System.out.println("好友名称: " + child_nodes.item(0).getTextContent());
 System.out.println("好友头像: " + child_nodes.item(1).getTextContent());
 }
 System.out.println();
 JSONObject friend_msg = new JSONObject();
 friend_msg.put("roleID", id);
 friend_msg.put("roleName", user_name);
 friend_msg.put("picURL", pic_url);
 friend_msg.put("photo", default_photo);
 return friend_msg;
 }
/**
 * 初始化玩家信息
 */
 public GamePlayer initGamePlayer(FacebookXmlRestClient client)
 throws FacebookException {
long uid = client.users_getLoggedInUser();
 List<Long> uids = new ArrayList<Long>(1);
 uids.add(uid);
List<ProfileField> initFields = new ArrayList<ProfileField>();
 initFields.add(ProfileField.FIRST_NAME);
 initFields.add(ProfileField.SEX);
 initFields.add(ProfileField.PIC);
// 获取角色在Facebook上的个人信息
 Document userInfoDoc = (Document) client
 .users_getInfo(uids, initFields);
// 名字
 NodeList fistNameDoc = userInfoDoc
 .getElementsByTagName(ProfileField.FIRST_NAME.toString());
 String firstName = fistNameDoc.item(0).getTextContent();
// 头像
 NodeList picDoc = userInfoDoc.getElementsByTagName(ProfileField.PIC
 .toString());
 String pic = picDoc.item(0).getTextContent();
// 性别
 NodeList sexDoc = userInfoDoc.getElementsByTagName(ProfileField.SEX
 .toString());
 boolean sex = splitSex(sexDoc.item(0).getTextContent());
InitTools initTools = InitTools.getInitTools();
 logger.info("用户名:" + firstName + " 头像地址:" + pic + "性别:" + sex);
GamePlayer gamePlayer = initTools.initGamePlayerInfor(uid, firstName,
 sex);
 gamePlayer.setRoleImage(pic);
// 将角色信息添加到在线列表
 long roleId = gamePlayer.getAccount().getRoleId();
 OnlineMap.addPlayer(roleId, gamePlayer);
// 将Facebook Connector 保存到缓存中
 gamePlayer.setClient(client);
 return gamePlayer;
 }
/**
 * 已经添加了该应用的角色信息
 */
 public ModelAndView sendInitClientMessage(long uid,
 HttpServletRequest request, HttpServletResponse response,
 FacebookXmlRestClient client) throws FacebookException,
 IOException, JSONException {
AccountDao accountDao = new AccountDao();
// 角色已经添加了该应用
 Account accountBean = accountDao.queryUserAccount(uid);
 Long roleID = accountBean.getRoleId();
 EmployeeFashionDao employeeFashionDao = new EmployeeFashionDao();
 EmployeeFashion employeeFashion = employeeFashionDao
 .queryEmployFashion(uid);
// 获取玩家信息
 GamePlayer gamePlayer = new GamePlayer();
 gamePlayer.setAccount(accountBean);
 gamePlayer.setEmployeeFashion(employeeFashion);
// 获取玩家的头像
 Document usr_pic_doc = null;
 try {
 usr_pic_doc = client.fql_query("SELECT pic FROM user WHERE uid="
 + uid);
 } catch (FacebookException e1) {
 e1.printStackTrace();
 }
 NodeList usr_pic_list = usr_pic_doc
 .getElementsByTagName(ProfileField.PIC.toString());
 String pic_url = usr_pic_list.item(0).getTextContent();
 gamePlayer.setRoleImage(pic_url);
JSONObject json_gameplayer = new JSONObject(gamePlayer
 .getObjectParamters());
 JSONArray json_employees = null;
 JSONObject commLoginMsg = new JSONObject();
// 好友信息
 EmployeesDao employeeDao = new EmployeesDao();
 Employees[] employees = employeeDao
 .queryEmployees(accountBean.getUid());
if (employees != null) {
 Shopkeepper[] shopkeeppers = new Shopkeepper[employees.length];
 for (int i = 0; i < employees.length; i++) {
 EmployeeFashion emloyeeFashion = employeeFashionDao
 .queryEmployFashion(uid);
 Shopkeepper shopkeepper = new Shopkeepper();
 shopkeepper.setEmployee(employees[i]);
 shopkeepper.setEmployeeFashion(emloyeeFashion);
Document doc = client.friends_get();
Long tmp_friends_id = employees[i].getRoleId();
// 获取好友的头像
 Document emp_pic_doc = client
 .fql_query("SELECT  pic FROM user WHERE uid="
 + tmp_friends_id);
 NodeList emp_pic_list = emp_pic_doc
 .getElementsByTagName(ProfileField.PIC.toString());
 String emp_url = emp_pic_list.item(0).getTextContent();
System.out.println("  查询到的用户的头像为 " + emp_url);
 shopkeepper.setEmployePhotoUrl(emp_url);
shopkeeppers[i] = shopkeepper;
 }
json_employees = new JSONArray();
 for (int i = 0; i < shopkeeppers.length; i++) {
 json_employees.put(new JSONObject(shopkeeppers[i]
 .getObjectParamters()));
 }
 // 初始化邮件未读数量
 List list = new MailDao().queryPersonAllMail(roleID);
MarketDao marketDao = new MarketDao();
 Market marketDto = marketDao.getMarketMessageByMarketID(roleID);
// 登陆初始化协议数据包
 commLoginMsg.put("event", "login");
 commLoginMsg.put("success", true);
 commLoginMsg.put("roleInfo", json_gameplayer);
 commLoginMsg.put("employee", json_employees);
 commLoginMsg.put("supermarket", this.getJSONMsg4Market(marketDto));
 commLoginMsg.put("room", this.getInnerMsg(roleID));
 commLoginMsg.put("bag", this.getBagInfor(roleID));
if (list.size() > 0) {
 HashMap[] mapObject = new HashMap[list.size()];
 HashMap mapSecond = new HashMap();
 for (int i = 0; i < list.size(); i++) {
HashMap map = new HashMap();
 Object[] object = (Object[]) list.get(i);
 map.put("mailID", object[0]);
 map.put("name", object[1]);
 map.put("time", object[2]);
 map.put("type", object[3]);
 map.put("flag", object[4]);
 mapObject[i] = map;
 }
 commLoginMsg.put("mail", mapObject);
 } else {
 commLoginMsg.put("mail", "");
 }
} else {
 commLoginMsg.put("event", "login");
 commLoginMsg.put("success", true);
 commLoginMsg.put("roleInfo", json_gameplayer);
 commLoginMsg.put("employee", "");
 commLoginMsg.put("mail", "");
 }
// 向客户端发送登陆初始化信息
 request.setAttribute("initData", commLoginMsg.toString());
 long roleId = gamePlayer.getAccount().getRoleId();
// 添加Facebook Connector Client
 gamePlayer.setClient(client);
// 将角色信息添加到在线列表
 OnlineMap.addPlayer(roleId, gamePlayer);
return new ModelAndView("./game/init.jsp");
 }
public JSONObject getJSONMsg4Market(Market market) throws JSONException {
 JSONObject supermarket = new JSONObject();
 supermarket.put("report", market.getReport());
 supermarket.put("depotLevel", market.getDepotLevel());
 supermarket.put("goodCount", market.getGoodCount());
 supermarket.put("count", market.getGoodCount());
 supermarket.put("salesCount", market.getSalesCount());
 supermarket.put("serviceCount", market.getServiceCount());
 supermarket.put("jobCount", market.getJobCount());
 supermarket.put("trash", market.getTrash());
 supermarket.put("goods", market.getGoods());
 supermarket.put("special", market.getSpecial());
 return supermarket;
 }
public JSONObject getInnerMsg(long roleId) throws JSONException {
JSONObject innerMsg = new JSONObject();
 innerMsg.put("size", 100000);
 innerMsg.put("extSize", 600000);
 innerMsg.put("floor", 10000);
 innerMsg.put("wall", "codeing");
 HouseInSideDao inner = new HouseInSideDao();
 List<Houseinside> itemsList = inner.querHouseInsideList(roleId);
 JSONArray items = new JSONArray();
 for (Iterator<Houseinside> iter = itemsList.iterator(); iter.hasNext();) {
 Houseinside inside = iter.next();
 JSONObject item = new JSONObject();
 item.put("ID", inside.getId());
 item.put("code", inside.getCode());
 item.put("x", inside.getPosX());
 item.put("y", inside.getPosY());
 item.put("direct", inside.getDirection());
 items.put(item);
 }
 innerMsg.put("items", items);
 return innerMsg;
 }
public JSONArray getBagInfor(long roleId) throws JSONException {
 BackPackDao bagDao = new BackPackDao();
 List list = bagDao.getArticlePartMessge(roleId);
 JSONArray json_array = new JSONArray();
for (Iterator<Backpack> iter = list.iterator(); iter.hasNext();) {
 Backpack bagItem = iter.next();
 JSONObject bag_item = new JSONObject();
 bag_item.put("code", bagItem.getCode());
 bag_item.put("class", bagItem.getCategory());
 bag_item.put("count", bagItem.getCount());
 json_array.put(bag_item);
 }
 return json_array;
 }
/**
 * 识别角色性别(支持简体中文和英文)
 *
 * @param sex
 * @return
 */
 private static boolean splitSex(String sex) {
 if (sex.equals("男") || sex.equalsIgnoreCase("male")) {
 return true;
 }
 return false;
 }
// 部门分配
 public void departmentPosition(HttpServletRequest request,
 HttpServletResponse response, JSONObject jsonObject) {
 // 设定玩家的数量,部门
 try {
 // 获取Data中的数据
 JSONObject oneItems = jsonObject.getJSONObject("data");
 Integer saleNumber = Integer.parseInt(oneItems
 .getString("saleNumber"));
 Integer managerNumber = Integer.parseInt(oneItems
 .getString("management"));
 long roleID = Integer.parseInt(oneItems.getString("roleID"));
// 设定部门编号跟数量
 System.out.println("销售部门人数为" + saleNumber);
 System.out.println("管理部门人数为" + managerNumber);
 Market market = new Market();
 market.setRoleId(roleID);
 market.setSalesCount(saleNumber);
 market.setServiceCount(managerNumber);
System.out.println("输出打印信息=======》");
 new MarketDao().saveMarketMessage(market);
// 给客户端传值
 JSONObject msg = new JSONObject();
 msg.put("event", "departManager");
 msg.put("sucess", true);
 try {
 PrintWriter out = response.getWriter();
 out.write(msg.toString());
 } catch (IOException e) {
 e.printStackTrace();
 }
 } catch (JSONException e) {
 e.printStackTrace();
 }
 System.out.println("程序执行结束=========>");
 }
public boolean userIsRegist(long uid) {
 AccountDao accountDao = new AccountDao();
 boolean result = accountDao.queryUserIsAddApps(uid);
 return result;
 }
// /////////////////////////////////////////////////////////////////////////
 // ///////////////////// 游戏初始化信息 ///////////////////////////////
 // /////////////////////////////////////////////////////////////////////////
static {
 // 加载.properties文件
 PropertyConfigurator.configure(PathUtil.getLog4jProperitesPath());
 }
private static final Logger logger = Logger
 .getLogger(LoginController.class);
private final static String UID = "uid";
// 好友信息查询语句
 static StringBuffer select_friends_sql = new StringBuffer(
 "SELECT name, pic FROM user WHERE uid=");
 // 用户图片信息查询语句
 static StringBuffer select_usr_pic_sql = new StringBuffer(
 "SELECT pic FROM user WHERE uid =");
 static final String User = "user";
static final String default_photo = "图片编码";
}