com.pureinfo.tgirls.servlet.GetWelcomeMsg.java Source code

Java tutorial

Introduction

Here is the source code for com.pureinfo.tgirls.servlet.GetWelcomeMsg.java

Source

/**
 * PureInfo TGirls
 * @(#)GetWelcomeMsg.java   1.0 2009-3-9
 * 
 * Copyright(c) 2004-2005, PureInfo Information Technology Corp. Ltd. 
 * All rights reserved, see the license file.
 * 
 * www.pureinfo.com.cn
 */

package com.pureinfo.tgirls.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import com.pureinfo.ark.ArkHelper;
import com.pureinfo.ark.content.ArkContentHelper;
import com.pureinfo.force.exception.PureException;
import com.pureinfo.tfr.cache.core.CacheManager;
import com.pureinfo.tfr.cache.core.IReadCache;
import com.pureinfo.tgirls.domain.IRandomEventMgr;
import com.pureinfo.tgirls.domain.IUserMgr;
import com.pureinfo.tgirls.json.model.JsonBase;
import com.pureinfo.tgirls.model.RandomEvent;
import com.pureinfo.tgirls.model.User;
import com.pureinfo.tgirls.model.helper.RandomEventConstants;
import com.pureinfo.tgirls.utils.servlet.CookieUtils;

public class GetWelcomeMsg extends HttpServlet {
    /**
     * Comment for <code>serialVersionUID</code>
     */
    private static final long serialVersionUID = 1L;

    private Logger logger = Logger.getLogger(this.getClass().getName());

    public static final String WELCOME_EVENT_KEY = "welcome.event";

    IReadCache cache = CacheManager.getReadFromDBCache("random.event");

    static int todayTotalScale = 0;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        JsonBase result = new JsonBase();
        response.setContentType("text/json; charset=utf-8");

        User loginUser = CookieUtils.getLoginUser(request, response);
        if (loginUser == null) {
            result.setErrorCode(JsonBase.ErrorCode.ERROR.getCode());
            result.setErrorMsg("");
            response.getWriter().write(result.toString());
            return;
        }

        IUserMgr usermgr = null;//(IUserMgr) ArkContentHelper.getContentMgrOf(User.class);
        try {
            usermgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class);
            if (loginUser.getLastLoginTime() == null) {
                loginUser.setLastLoginTime(new Date());
                usermgr.save(loginUser);
            }
        } catch (PureException e1) {
            logger.error(e1);
            result.setErrorCode(JsonBase.ErrorCode.ERROR.getCode());
            if (StringUtils.isNotEmpty(e1.getMessage())) {
                result.setErrorMsg(e1.getMessage());
            } else {
                result.setErrorMsg("");
            }
            response.getWriter().write(result.toString());
            return;
        }

        if (DateUtils.isSameDay(loginUser.getLastLoginTime(), new Date())) {
            result.setErrorCode(JsonBase.ErrorCode.ERROR.getCode());
            result.setErrorMsg("???");
            response.getWriter().write(result.toString());
            return;
        } else {
            //????
            createNormalRandomEvent(loginUser);
        }

        Calendar now = Calendar.getInstance();
        int m = now.get(Calendar.MONTH);
        int d = now.get(Calendar.DAY_OF_MONTH);

        List<RandomEvent> todayEvents = (List<RandomEvent>) cache.get(WELCOME_EVENT_KEY + "." + m + "." + d);
        if (todayEvents == null) {
            todayEvents = new ArrayList<RandomEvent>();

            logger.debug("today events is empty. reload.");

            List<RandomEvent> allWelcomeRandomEvents = null;
            try {
                allWelcomeRandomEvents = getWelcomeEvents();
            } catch (PureException e) {
                logger.error("error when get welcome events.", e);
            }

            if (allWelcomeRandomEvents == null || allWelcomeRandomEvents.isEmpty()) {

                logger.debug("all welcome events is empty.");

                result.setErrorCode(JsonBase.ErrorCode.ERROR.getCode());
                result.setErrorMsg("?");
                response.getWriter().write(result.toString());
                return;
            }

            List<RandomEvent> normalEvents = new ArrayList<RandomEvent>();// 

            Calendar c1 = Calendar.getInstance();// Calendar.getInstance();
            Calendar today = Calendar.getInstance();
            for (Iterator<RandomEvent> iterator = allWelcomeRandomEvents.iterator(); iterator.hasNext();) {
                RandomEvent randomEvent = iterator.next();
                String month_day = randomEvent.getEventMonthDay();
                if (StringUtils.isNotEmpty(month_day)) {
                    try {
                        int i = month_day.indexOf("-");
                        int month = NumberUtils.toInt(month_day.substring(0, i), -1);
                        int day = NumberUtils.toInt(month_day.substring(i + 1), -1);
                        c1.clear();
                        c1 = Calendar.getInstance();

                        //                        logger.debug("the random event [" + randomEvent.getEventInfo() + "]  month:" + month
                        //                                + " ,day: " + day);

                        if (month != -1) {
                            c1.set(Calendar.MONTH, month - 1);
                        }
                        if (day != -1) {
                            c1.set(Calendar.DAY_OF_MONTH, day);
                        }

                        if (DateUtils.isSameDay(c1, today)) {
                            todayEvents.add(randomEvent);
                        }
                    } catch (Exception e) {
                    }
                } else {
                    normalEvents.add(randomEvent);
                }
            }

            if (todayEvents == null || todayEvents.isEmpty()) {
                if (normalEvents.isEmpty()) {

                    logger.debug("today events is empty, and normal events is empty too.");

                    result.setErrorCode(JsonBase.ErrorCode.ERROR.getCode());
                    result.setErrorMsg("?");
                    response.getWriter().write(result.toString());
                    return;
                } else {
                    todayEvents.addAll(normalEvents);
                }
            }

            Collections.sort(todayEvents, new BeanComparator("eventScale"));
            todayTotalScale = 0;
            for (Iterator<RandomEvent> iterator = todayEvents.iterator(); iterator.hasNext();) {
                RandomEvent randomEvent2 = iterator.next();
                todayTotalScale += randomEvent2.getEventScale();
            }
            cache.put(WELCOME_EVENT_KEY + "." + m + "." + d, todayEvents);

        }

        if (todayEvents == null || todayEvents.isEmpty()) {
            logger.debug("today events is empty, system events is empty .");

            result.setErrorCode(JsonBase.ErrorCode.ERROR.getCode());
            result.setErrorMsg("?");
            response.getWriter().write(result.toString());
            return;
        }

        int random = new Random().nextInt(todayTotalScale);
        RandomEvent todayEvent = null;
        int start = 0;
        int end = 0;
        for (int i = 0; i < todayEvents.size(); i++) {
            if (i == 0) {
                start = 0;
                end = todayEvents.get(i).getEventScale();
            } else {
                start = end;
                end = end + todayEvents.get(i).getEventScale();
            }

            if (random >= start && random < end) {
                todayEvent = todayEvents.get(i);
                break;
            }
        }
        if (todayEvent == null) {
            result.setErrorCode(JsonBase.ErrorCode.ERROR.getCode());
            result.setErrorMsg("?");
            response.getWriter().write(result.toString());
            return;
        }

        try {
            result.put("event", new JSONObject(todayEvent));

            logger.info("welcome event[" + todayEvent.getEventInfo() + "]");

            loginUser.setFunds(loginUser.getFunds() + todayEvent.getEventMoney());
            loginUser.setAssets(loginUser.getAssets() + todayEvent.getEventMoney());
            loginUser.setLastLoginTime(new Date());

            usermgr.save(loginUser);

            request.getSession().setAttribute(ArkHelper.ATTR_LOGIN_USER, loginUser);

        } catch (Exception e) {
            logger.error(e);
            result.setErrorCode(JsonBase.ErrorCode.ERROR.getCode());
            if (StringUtils.isNotEmpty(e.getMessage())) {
                result.setErrorMsg(e.getMessage());
            } else {
                result.setErrorMsg("");
            }
            response.getWriter().write(result.toString());
            return;
        }

        logger.debug("event:" + result.toString());

        request.getSession().setAttribute(ArkHelper.ATTR_LOGIN_USER, loginUser);
        response.getWriter().write(result.toString());
        return;
    }

    private void createNormalRandomEvent(User _loginUser) {
        try {
            NormalRandomEventMsg.getInstance().createEvent(_loginUser);
        } catch (Exception e) {
            logger.error("error when create normal random event.", e);
        }

    }

    private List<RandomEvent> getWelcomeEvents() throws PureException {
        IRandomEventMgr mgr = (IRandomEventMgr) ArkContentHelper.getContentMgrOf(RandomEvent.class);
        return mgr.getEventByType(RandomEventConstants.EventType.WELCOME_EVENT);
    }
}