Java tutorial
/** * PureInfo TGirls * @(#)SNSEntryServlet.java 1.0 2009-3-11 * * Copyright(c) 2004-2005, PureInfo Information Technology Corp. Ltd. * All rights reserved, see the license file. * * www.pureinfo.com.cn */ package com.pureinfo.tgirls.sns.servlet; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Date; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import com.pureinfo.ark.ArkHelper; import com.pureinfo.ark.content.ArkContentHelper; import com.pureinfo.dolphin.context.LocalContextHelper; import com.pureinfo.force.exception.PureException; import com.pureinfo.tgirls.domain.IUserMgr; import com.pureinfo.tgirls.model.User; import com.pureinfo.tgirls.model.helper.UserConstants; import com.pureinfo.tgirls.sns.TOPAPI; import com.pureinfo.tgirls.sns.constants.APPConstants; import com.pureinfo.tgirls.sns.constants.SessionConstants; import com.pureinfo.tgirls.utils.script.ScriptWriteUtils; import com.pureinfo.tgirls.utils.servlet.CookieUtils; import com.taobao.api.sns.common.TaobaoApiException; import com.taobao.api.sns.common.TipBean; import com.taobao.api.sns.common.TipUtil; import com.taobao.api.sns.response.ObjResponse; public class SNSEntryServlet extends HttpServlet { /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 1L; private IUserMgr userMgr; private Logger logger = Logger.getLogger(this.getClass().getName()); @Override protected void doGet(HttpServletRequest _req, HttpServletResponse _resp) throws ServletException, IOException { this.doPost(_req, _resp); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("tgirls sns entry."); String taobaoUserId = null; String taobaoUserName = null; String topSession = request.getParameter(APPConstants.REQ_PARAMETER_SESSION); String topParameters = request.getParameter(APPConstants.REQ_PARAMETER_PARAMETERS); String topSign = request.getParameter(APPConstants.REQ_PARAMETER_SIGN); TipBean tb = null; try { tb = TipUtil.beforeFetch(topSession, topParameters, topSign, APPConstants.SECRET); if (!tb.isOk()) { logger.error("top api failed." + tb.getErrMsg()); throw new Exception("TOP API failed:" + tb.getErrMsg()); } taobaoUserId = tb.getUserId() + ""; taobaoUserName = tb.getUserNick(); logger.debug("id:" + taobaoUserId); logger.debug("name:" + taobaoUserName); logger.debug("session:" + topSession); if ("0".equals(taobaoUserId) || StringUtils.isEmpty(taobaoUserId) || StringUtils.isEmpty(taobaoUserName)) { throw new Exception("parameter empty."); } } catch (Exception e) { logger.error("error when call top API.", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "top system error." + e.getMessage()); return; } HttpSession session = request.getSession(true); session.removeAttribute(ArkHelper.ATTR_LOGIN_USER); User loginUser = null;//(User) session.getAttribute(ArkHelper.ATTR_LOGIN_USER); //loginUser = CookieUtils.getLoginUser(request, response); if (loginUser != null && loginUser.getTaobaoID().equals(taobaoUserId)) { logger.debug("user " + taobaoUserId + " already logined."); } else { try { userMgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class); if (!userMgr.isUserExists(taobaoUserId)) { loginUser = createUser(taobaoUserId, topSession); //ScriptWriteUtils.reBuildUserInfoScript(loginUser); try { //ScriptWriteUtils.reBuildUserBuyPhotosScript(loginUser); //ScriptWriteUtils.reBuildUserUploadPhotosScript(loginUser); } catch (Exception e) { logger.error("error when rebuild buy and upload scripts.", e); } } else { loginUser = userMgr.getUserByTaobaoId(taobaoUserId); } } catch (PureException e) { logger.error("tgirls system error.", e); response.sendError(HttpServletResponse.SC_BAD_GATEWAY, "tgirls system error." + e.getMessage()); return; } catch (NumberFormatException e) { logger.error("number format error.", e); response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); return; } catch (TaobaoApiException e) { logger.error("top system error.", e); response.sendError(HttpServletResponse.SC_BAD_GATEWAY, "top system error." + e.getMessage()); return; } } if (loginUser == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "can not find current user."); return; } if (loginUser.getFunds() <= UserConstants.DISUSE_FUNDS || loginUser.getAssets() <= UserConstants.DISUSE_ASSETS) { response.sendRedirect(request.getContextPath() + "/disable.html"); return; } updateUserHeadImg(loginUser, topSession); session.setAttribute(ArkHelper.ATTR_LOGIN_USER, loginUser); session.setAttribute(SessionConstants.TAOBAO_SESSION_ID, topSession); LocalContextHelper.setAttribute(SessionConstants.TAOBAO_SESSION_ID, topSession); addCookie(loginUser, request, response); // System.out.println("========================"); // // // Cookie[] cs = request.getCookies(); // for (int i = 0; i < cs.length; i++) { // Cookie c = cs[i]; // System.out.println("cookie[" + c.getName() + "]:" + c.getValue()); // } // RequestDispatcher rd = request.getRequestDispatcher("/index.html"); rd.forward(request, response); //response.sendRedirect(request.getContextPath()); return; } private void addCookie(User _loginUser, HttpServletRequest _request, HttpServletResponse _response) throws UnsupportedEncodingException { Cookie name = new Cookie(CookieUtils.NAME, URLEncoder.encode(_loginUser.getName(), "utf-8")); Cookie nickName = new Cookie(CookieUtils.NICK_NAME, URLEncoder.encode(_loginUser.getNickname(), "utf-8")); Cookie taobaoId = new Cookie(CookieUtils.TAOBAO_ID, URLEncoder.encode(_loginUser.getTaobaoID(), "utf-8")); Cookie img = new Cookie(CookieUtils.HEAD_IMG, URLEncoder.encode(_loginUser.getHeadImg(), "utf-8")); Cookie topsession = new Cookie(CookieUtils.TOP_SESSION_ID, _request.getParameter(APPConstants.REQ_PARAMETER_SESSION)); _response.addCookie(name); _response.addCookie(nickName); _response.addCookie(taobaoId); _response.addCookie(img); _response.addCookie(topsession); } private void updateUserHeadImg(User _loginUser, String _topSession) { logger.debug("update user head img..."); ObjResponse<com.taobao.api.sns.pojo.user.User> taobaoResponse; try { taobaoResponse = TOPAPI.getInstance().getUser(Long.parseLong(_loginUser.getTaobaoID()), _topSession); if (taobaoResponse.isSuccess()) { com.taobao.api.sns.pojo.user.User tu = taobaoResponse.getObj(); if (tu == null) { logger.debug("the user info from top system is empty. return."); return; } String h = _loginUser.getHeadImg(); String h2 = tu.getPicURL(); if (StringUtils.isEmpty(h2)) { logger.debug("the head img from top system is empty."); return; } if (StringUtils.isEmpty(h) || !h.equalsIgnoreCase(h2)) { _loginUser.setHeadImg(h2); if (userMgr == null) { userMgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class); } userMgr.save(_loginUser); } } } catch (Exception e) { logger.error("error when update head img.", e); } } /** * first entry. create user. * * @param _taobaoUserName * @param _taobaoUserId * * @return * @throws TaobaoApiException * @throws NumberFormatException * @throws PureException * @throws PureException */ private User createUser(String _taobaoUserId, String _topSession) throws NumberFormatException, TaobaoApiException, PureException { logger.debug("user first entry. create user info."); ObjResponse<com.taobao.api.sns.pojo.user.User> taobaoResponse = TOPAPI.getInstance() .getUser(Long.parseLong(_taobaoUserId), _topSession); if (taobaoResponse.isSuccess()) { User u = new User(); com.taobao.api.sns.pojo.user.User tu = taobaoResponse.getObj(); if (tu == null) { throw new TaobaoApiException("response success,but object is empty"); } u.setHeadImg(tu.getPicURL()); u.setName(tu.getNick()); u.setAdminType(tu.getNick().equalsIgnoreCase(UserConstants.SYSTEM_SUPER_ADMIN_NAME) ? UserConstants.AdminType.SUPER_ADMIN : UserConstants.AdminType.NOT_ADMIN); u.setAssets(0); u.setBuyPhotosNum(0); u.setAuditUserName(null); u.setAuditUserNickName(null); u.setAuditUserTaobaoId(null); u.setCreateTime(); // ???toJsonObject u.setFunds(0); u.setSex(UserConstants.Sex.UNKNOWN); u.setLastLoginTime(new Date(1, 1, 1)); u.setNickname(tu.getRealname()); u.setShopLevel(1); u.setShopPost(null); u.setShopSize(10); u.setShopTitle(null); u.setUploadPhotosNum(0); u.setTaobaoID(_taobaoUserId); userMgr.save(u); return u; } else { throw new RuntimeException(taobaoResponse.getMsg()); } } }