Example usage for java.util Calendar getActualMaximum

List of usage examples for java.util Calendar getActualMaximum

Introduction

In this page you can find the example usage for java.util Calendar getActualMaximum.

Prototype

public int getActualMaximum(int field) 

Source Link

Document

Returns the maximum value that the specified calendar field could have, given the time value of this Calendar.

Usage

From source file:cn.jcenterhome.web.action.CpAction.java

public ActionForward cp_event(HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> sGlobal = (Map<String, Object>) request.getAttribute("sGlobal");
    Map<String, Object> sConfig = (Map<String, Object>) request.getAttribute("sConfig");
    Map<String, Object> space = (Map<String, Object>) request.getAttribute("space");
    Map<Integer, String> sNames = (Map<Integer, String>) request.getAttribute("sNames");
    int supe_uid = (Integer) sGlobal.get("supe_uid");
    String supe_username = (String) sGlobal.get("supe_username");
    int timestamp = (Integer) sGlobal.get("timestamp");
    int eventid = 0;
    String tempS = request.getParameter("id");
    if (tempS != null) {
        eventid = Common.intval(tempS);/*  ww  w . j  a  v a 2  s  .  c  om*/
    }
    tempS = request.getParameter("op");
    String op = Common.empty(tempS) ? "edit" : tempS;
    Map<String, String> menus = new HashMap<String, String>();
    menus.put(op, " class='active'");
    boolean allowmanage = false;
    List<Map<String, Object>> query;
    Map<String, Object> event = null;
    if (eventid != 0) {
        query = dataBaseService.executeQuery("SELECT e.*, ef.* FROM " + JavaCenterHome.getTableName("event")
                + " e LEFT JOIN " + JavaCenterHome.getTableName("eventfield")
                + " ef ON e.eventid=ef.eventid WHERE e.eventid='" + eventid + "'");
        event = query.size() > 0 ? query.get(0) : null;
        if (event == null) {
            return showMessage(request, response, "event_does_not_exist");
        }
        int eventGrade = (Integer) event.get("grade");
        int eventUid = (Integer) event.get("uid");
        if ((eventGrade == -1 || eventGrade == 0) && eventUid != supe_uid
                && !Common.checkPerm(request, response, "manageevent")) {
            return showMessage(request, response, "event_under_verify");
        }
        query = dataBaseService.executeQuery("SELECT * FROM " + JavaCenterHome.getTableName("userevent")
                + " WHERE eventid='" + eventid + "' AND uid='" + supe_uid + "'");
        Map<String, Object> value = query.size() > 0 ? query.get(0) : new HashMap<String, Object>();
        sGlobal.put("supe_userevent", value);
        Integer status = (Integer) value.get("status");
        if ((status != null && status >= 3) || Common.checkPerm(request, response, "manageevent")) {
            allowmanage = true;
        }
    }
    Map<Integer, Map<String, Object>> globalEventClass = Common.getCacheDate(request, response,
            "/data/cache/cache_eventclass.jsp", "globalEventClass");
    if (Common.empty(globalEventClass)) {
        try {
            cacheService.eventclass_cache();
        } catch (IOException e) {
            e.printStackTrace();
            return showMessage(request, response, e.getMessage());
        }
        globalEventClass = Common.getCacheDate(request, response, "/data/cache/cache_eventclass.jsp",
                "globalEventClass");
    }
    FileUploadUtil upload;
    try {
        upload = getParsedFileUploadUtil(request);
        if (submitCheckForMulti(request, upload, "eventsubmit")) {
            if (Common.checkPerm(request, response, "seccode") && !cpService.checkSeccode(request, response,
                    sGlobal, sConfig, upload.getParameter("seccode"))) {
                return showMessage(request, response, "incorrect_code");
            }
            Map<String, Object> arr1 = new HashMap<String, Object>();
            String arr1Title;
            try {
                arr1Title = Common.getStr(upload.getParameter("title"), 80, true, true, true, 0, 0, request,
                        response);
            } catch (Exception exception) {
                return showMessage(request, response, exception.getMessage());
            }
            arr1.put("title", arr1Title);
            arr1.put("classid", Common.intval(upload.getParameter("classid")));
            try {
                arr1.put("province", Common.getStr(upload.getParameter("province"), 20, true, true, false, 0, 0,
                        request, response));
            } catch (Exception exception) {
                return showMessage(request, response, exception.getMessage());
            }
            try {
                arr1.put("city", Common.getStr(upload.getParameter("city"), 20, true, true, false, 0, 0,
                        request, response));
            } catch (Exception exception) {
                return showMessage(request, response, exception.getMessage());
            }
            try {
                arr1.put("location", Common.getStr(upload.getParameter("location"), 80, true, true, true, 0, 0,
                        request, response));
            } catch (Exception exception) {
                return showMessage(request, response, exception.getMessage());
            }
            String timeoffset = Common.getTimeOffset(sGlobal, sConfig);
            int arr1Starttime = Common.strToTime(upload.getParameter("starttime"), timeoffset,
                    "yyyy-MM-dd HH:mm");
            arr1.put("starttime", arr1Starttime);
            int arr1Endtime = Common.strToTime(upload.getParameter("endtime"), timeoffset, "yyyy-MM-dd HH:mm");
            arr1.put("endtime", arr1Endtime);
            int arr1Deadline = Common.strToTime(upload.getParameter("deadline"), timeoffset,
                    "yyyy-MM-dd HH:mm");
            arr1.put("deadline", arr1Deadline);
            arr1.put("public", Common.intval(upload.getParameter("public")));
            Map<String, Object> arr2 = new HashMap<String, Object>();
            try {
                arr2.put("detail", Common.getStr(upload.getParameter("detail"), 0, true, true, true, 0, 1,
                        request, response));
            } catch (Exception exception) {
                return showMessage(request, response, exception.getMessage());
            }
            arr2.put("limitnum", Common.intval(upload.getParameter("limitnum")));
            arr2.put("verify", Common.intval(upload.getParameter("verify")));
            arr2.put("allowpost", Common.intval(upload.getParameter("allowpost")));
            arr2.put("allowpic", Common.intval(upload.getParameter("allowpic")));
            arr2.put("allowfellow", Common.intval(upload.getParameter("allowfellow")));
            arr2.put("allowinvite", Common.intval(upload.getParameter("allowinvite")));
            try {
                arr2.put("template", Common.getStr(upload.getParameter("template"), 255, true, true, true, 0, 0,
                        request, response));
            } catch (Exception exception) {
                return showMessage(request, response, exception.getMessage());
            }
            if (Common.empty(arr1.get("title"))) {
                return showMessage(request, response, "event_title_empty");
            } else if (Common.empty(arr1.get("classid"))) {
                return showMessage(request, response, "event_classid_empty");
            } else if (Common.empty(arr1.get("city"))) {
                return showMessage(request, response, "event_city_empty");
            } else if (Common.empty(arr2.get("detail"))) {
                return showMessage(request, response, "event_detail_empty");
            } else if (arr1Endtime - arr1Starttime > 60 * 24 * 3600) {
                return showMessage(request, response, "event_bad_time_range");
            } else if (arr1Endtime < arr1Starttime) {
                return showMessage(request, response, "event_bad_endtime");
            } else if (arr1Deadline > arr1Endtime) {
                return showMessage(request, response, "event_bad_deadline");
            } else if (eventid == 0 && arr1Starttime < timestamp) {
                return showMessage(request, response, "event_bad_starttime");
            }
            Map<String, Object> pic = null;
            if (upload.isMultipart()) {
                FileItem fileItem = upload.getFileItem("poster");
                Object picob = cpService.savePic(request, response, fileItem, "-1", arr1Title, 0);
                if (Common.isArray(picob)) {
                    pic = (Map<String, Object>) picob;
                    if (!Common.empty(pic.get("filepath"))) {
                        arr1.put("poster", pic.get("filepath"));
                        arr1.put("thumb", pic.get("thumb"));
                        arr1.put("remote", pic.get("remote"));
                    }
                }
            }
            String tagidString = upload.getParameter("tagid");
            int tagid = 0;
            if (!Common.empty(tagidString) && (eventid == 0 || ((Integer) event.get("uid") == supe_uid)
                    && !tagidString.equals(String.valueOf(event.get("tagid"))))) {
                tagid = Common.intval(tagidString);
                query = dataBaseService.executeQuery("SELECT * FROM " + JavaCenterHome.getTableName("tagspace")
                        + " WHERE tagid='" + tagid + "' AND uid='" + supe_uid + "' LIMIT 1");
                Map<String, Object> value = query.size() > 0 ? query.get(0) : null;
                if (value != null) {
                    if ((Integer) value.get("grade") == 9) {
                        arr1.put("tagid", value.get("tagid"));
                    }
                }
            }
            if (eventid != 0) {
                if (allowmanage) {
                    if ((Integer) event.get("grade") == -1 && (Integer) event.get("uid") == supe_uid) {
                        arr1.put("grade", 0);
                    }
                    Map<String, Object> whereData = new HashMap<String, Object>();
                    whereData.put("eventid", eventid);
                    dataBaseService.updateTable("event", arr1, whereData);
                    dataBaseService.updateTable("eventfield", arr2, whereData);
                    tempS = upload.getParameter("sharepic");
                    if (!Common.empty(tempS) && pic != null && !Common.empty(pic.get("picid"))) {
                        Map<String, Object> arr = new HashMap<String, Object>();
                        arr.put("eventid", eventid);
                        arr.put("picid", pic.get("picid"));
                        arr.put("uid", supe_uid);
                        arr.put("username", supe_username);
                        arr.put("dateline", timestamp);
                        dataBaseService.insertTable("eventpic", arr, false, false);
                    }
                    return showMessage(request, response, "do_success", "space.jsp?do=event&id=" + eventid, 0);
                } else {
                    return showMessage(request, response, "no_privilege_edit_event");
                }
            } else {
                if (!cpService.checkRealName(request, "event")) {
                    return showMessage(request, response, "no_privilege_realname");
                }
                if (!cpService.checkVideoPhoto(request, response, "event")) {
                    return showMessage(request, response, "no_privilege_videophoto");
                }
                switch (cpService.checkNewUser(request, response)) {
                case 1:
                    break;
                case 2:
                    return showMessage(request, response, "no_privilege_newusertime", "", 1,
                            String.valueOf(sConfig.get("newusertime")));
                case 3:
                    return showMessage(request, response, "no_privilege_avatar");
                case 4:
                    return showMessage(request, response, "no_privilege_friendnum", "", 1,
                            String.valueOf(sConfig.get("need_friendnum")));
                case 5:
                    return showMessage(request, response, "no_privilege_email");
                }
                int topicid = cpService.checkTopic(request, Common.intval(upload.getParameter("topicid")),
                        "event");
                arr1.put("topicid", topicid);
                arr1.put("uid", supe_uid);
                arr1.put("username", supe_username);
                arr1.put("dateline", timestamp);
                arr1.put("updatetime", timestamp);
                arr1.put("membernum", 1);
                arr1.put("grade",
                        !Common.empty(Common.checkPerm(request, response, sGlobal, "verifyevent")) ? 0 : 1);
                eventid = dataBaseService.insertTable("event", arr1, true, false);
                if (eventid == 0) {
                    return showMessage(request, response, "event_create_failed");
                }
                arr2.put("eventid", eventid);
                arr2.put("hotuser", "");
                dataBaseService.insertTable("eventfield", arr2, false, false);
                tempS = upload.getParameter("sharepic");
                if (!Common.empty(tempS) && pic != null && !Common.empty(pic.get("picid"))) {
                    Map<String, Object> arr = new HashMap<String, Object>();
                    arr.put("eventid", eventid);
                    arr.put("picid", pic.get("picid"));
                    arr.put("uid", supe_uid);
                    arr.put("username", supe_username);
                    arr.put("dateline", timestamp);
                    dataBaseService.insertTable("eventpic", arr, false, false);
                }
                Map<String, Object> arr3 = new HashMap<String, Object>();
                arr3.put("eventid", eventid);
                arr3.put("uid", supe_uid);
                arr3.put("username", supe_username);
                arr3.put("status", 4);
                arr3.put("fellow", 0);
                tempS = (String) arr1.get("template");
                tempS = tempS == null ? "" : tempS;
                arr3.put("template", tempS);
                arr3.put("dateline", timestamp);
                dataBaseService.insertTable("userevent", arr3, false, false);
                if ((Integer) arr1.get("grade") > 0) {
                    tempS = upload.getParameter("makefeed");
                    if (!Common.empty(tempS)) {
                        feedService.feedPublish(request, response, eventid, "eventid", true);
                    }
                }
                cpService.updateStat(request, "event", false);
                String eventnumsql;
                if (Common.empty(space.get("eventnum"))) {
                    Map<String, Object> whereArr = new HashMap<String, Object>();
                    whereArr.put("uid", space.get("uid"));
                    space.put("eventnum", Common.getCount("event", whereArr, null));
                    eventnumsql = "eventnum=" + space.get("eventnum");
                } else {
                    eventnumsql = "eventnum=eventnum+1";
                }
                Map<String, Integer> reward = Common.getReward("createevent", false, 0, "", true, request,
                        response);
                dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("space") + " SET "
                        + eventnumsql + ", lastpost='" + timestamp + "', updatetime='" + timestamp
                        + "', credit=credit+" + reward.get("credit") + ", experience=experience+"
                        + reward.get("experience") + " WHERE uid='" + supe_uid + "'");
                String url;
                if (topicid != 0) {
                    cpService.topicJoin(request, topicid, supe_uid, supe_username);
                    url = "space.jsp?do=topic&topicid=" + topicid + "&view=event";
                } else {
                    url = "space.jsp?do=event&id=" + eventid;
                }
                return showMessage(request, response, "do_success", url, 0);
            }
        }
        if ("invite".equals(op)) {
            Map<String, Object> supeUserEvent = (Map<String, Object>) sGlobal.get("supe_userevent");
            if (((event == null || Common.empty(event.get("allowinvite")))
                    && (supeUserEvent == null || (Integer) supeUserEvent.get("status") < 3))
                    || (supeUserEvent == null || (Integer) supeUserEvent.get("status") < 2)) {
                return showMessage(request, response, "no_privilege_do_eventinvite");
            }
            if (submitCheck(request, "invitesubmit")) {
                Map<String, Object> arr = new LinkedHashMap<String, Object>();
                arr.put("uid", supe_uid);
                arr.put("username", supe_username);
                arr.put("eventid", eventid);
                arr.put("dateline", timestamp);
                List<String> inserts = new ArrayList<String>();
                List<Integer> touids = new ArrayList<Integer>();
                String[] ids = request.getParameterValues("ids[]");
                if (ids != null) {
                    try {
                        StringBuilder builder = new StringBuilder();
                        int touid;
                        for (int i = 0; i < ids.length; i++) {
                            touid = Common.intval(ids[i]);
                            arr.put("touid", touid);
                            arr.put("tousername", Common.getStr(request.getParameterValues("names[]")[i], 15,
                                    true, true, false, 0, 0, request, response));
                            builder.append("(");
                            builder.append(Common.sImplode(arr));
                            builder.append(")");
                            inserts.add(builder.toString());
                            touids.add(touid);
                            builder.delete(0, builder.length());
                        }
                    } catch (Exception exception) {
                        return showMessage(request, response, exception.getMessage());
                    }
                }
                if (!Common.empty(inserts)) {
                    dataBaseService.execute("INSERT INTO " + JavaCenterHome.getTableName("eventinvite")
                            + "(uid, username, eventid, dateline, touid, tousername) VALUES "
                            + Common.implode(inserts, ","));
                    dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("space")
                            + " SET eventinvitenum=eventinvitenum+1 WHERE uid IN (" + Common.sImplode(touids)
                            + ")");
                }
                tempS = request.getParameter("group");
                int getGroup = !Common.empty(tempS) ? Common.intval(tempS) : -1;
                tempS = request.getParameter("page");
                int getPage = Common.empty(tempS) ? 0 : Common.intval(tempS);
                return showMessage(request, response, "do_success",
                        "cp.jsp?ac=event&op=invite&id=" + eventid + "&group=" + getGroup + "&page=" + getPage,
                        2);
            }
            int perpage = 21;
            tempS = request.getParameter("page");
            int page = Common.empty(tempS) ? 0 : Common.intval(tempS);
            if (page < 1)
                page = 1;
            int start = (page - 1) * perpage;
            int maxPage = (Integer) sConfig.get("maxpage");
            if ((tempS = Common.ckStart(start, perpage, maxPage)) != null) {
                return showMessage(request, response, tempS);
            }
            List<String> wherearr = new ArrayList<String>();
            String key = Common.stripSearchKey(request.getParameter("key"));
            if (!Common.empty(key)) {
                wherearr.add(" fusername LIKE '%" + key + "%' ");
            }
            tempS = request.getParameter("group");
            int group = !Common.empty(tempS) ? Common.intval(tempS) : -1;
            if (group >= 0) {
                wherearr.add(" gid='" + group + "'");
            }
            String sql = wherearr.size() > 0 ? "AND" + Common.implode(wherearr, " AND ") : "";
            query = dataBaseService
                    .executeQuery("SELECT COUNT(*) AS cont FROM " + JavaCenterHome.getTableName("friend")
                            + " WHERE uid='" + supe_uid + "' AND status='1' " + sql);
            int count = query.size() > 0 ? (Integer) (query.get(0).get("cont")) : 0;
            List<Integer> fuids = new ArrayList<Integer>();
            List<Map<String, Object>> list = null;
            if (count != 0) {
                query = dataBaseService.executeQuery("SELECT * FROM " + JavaCenterHome.getTableName("friend")
                        + " WHERE uid='" + supe_uid + "' AND status='1' " + sql
                        + " ORDER BY num DESC, dateline DESC LIMIT " + start + "," + perpage);
                int fuid;
                for (Map<String, Object> value : query) {
                    fuid = (Integer) value.get("fuid");
                    Common.realname_set(sGlobal, sConfig, sNames, fuid, (String) value.get("fusername"), "", 0);
                    fuids.add(fuid);
                }
                list = query;
            }
            Map<Integer, Integer> joins = new HashMap<Integer, Integer>();
            if (fuids.size() > 0) {
                query = dataBaseService.executeQuery(
                        "SELECT uid FROM " + JavaCenterHome.getTableName("userevent") + " WHERE eventid='"
                                + eventid + "' AND uid IN (" + Common.sImplode(fuids) + ") AND status > 1");
                int vuid;
                for (Map<String, Object> value : query) {
                    vuid = (Integer) value.get("uid");
                    joins.put(vuid, vuid);
                }
                query = dataBaseService.executeQuery(
                        "SELECT touid FROM " + JavaCenterHome.getTableName("eventinvite") + " WHERE eventid='"
                                + eventid + "' AND touid IN (" + Common.sImplode(fuids) + ")");
                for (Map<String, Object> value : query) {
                    vuid = (Integer) value.get("touid");
                    joins.put(vuid, vuid);
                }
            }
            Map<Integer, String> groups = Common.getFriendGroup(request);
            Map<Integer, String> groupselect = new HashMap<Integer, String>();
            groupselect.put(group, " selected");
            String multi = Common.multi(request, count, perpage, page, maxPage,
                    "cp.jsp?ac=event&op=invite&id=" + eventid + "&group=" + group + "&key=" + key, null, null);
            request.setAttribute("group", group);
            request.setAttribute("page", page);
            request.setAttribute("list", list);
            request.setAttribute("joins", joins);
            request.setAttribute("multi", multi);
            request.setAttribute("groups", groups);
        } else if ("members".equals(op)) {
            Map<String, Object> supeUserEvent = (Map<String, Object>) sGlobal.get("supe_userevent");
            if (supeUserEvent == null || (Integer) supeUserEvent.get("status") < 3) {
                return showMessage(request, response, "no_privilege_manage_event_members");
            }
            if (submitCheck(request, "memberssubmit")) {
                String[] ids = request.getParameterValues("ids[]");
                boolean rz;
                if (!Common.empty(ids)) {
                    Object object = verify_eventmembers(request, sGlobal, event, ids,
                            request.getParameter("newstatus"));
                    if (object instanceof MessageVO) {
                        return showMessage(request, response, (MessageVO) object);
                    }
                    rz = !Common.empty(object);
                } else {
                    rz = false;
                }
                String status = request.getParameter("status");
                status = status == null ? "" : status;
                if (rz) {
                    return showMessage(request, response, "do_success",
                            "cp.jsp?ac=event&op=members&id=" + eventid + "&status=" + status, 2);
                } else {
                    return showMessage(request, response, "choose_right_eventmember",
                            "cp.jsp?ac=event&op=members&id=" + eventid + "&status=" + status, 5);
                }
            }
            int perpage = 24;
            tempS = request.getParameter("start");
            int start = Common.empty(tempS) ? 0 : Common.intval(tempS);
            int count = 0;
            String wheresql;
            String key = request.getParameter("key");
            String status = request.getParameter("status");
            if (!Common.empty(key)) {
                key = Common.stripSearchKey(key);
                wheresql = " AND username LIKE '%" + key + "%' ";
            } else {
                status = Common.intval(status) + "";
                wheresql = " AND status='" + status + "'";
            }
            int maxPage = (Integer) sConfig.get("maxpage");
            if ((tempS = Common.ckStart(start, perpage, maxPage)) != null) {
                return showMessage(request, response, tempS);
            }
            query = dataBaseService.executeQuery("SELECT * FROM " + JavaCenterHome.getTableName("userevent")
                    + " WHERE eventid='" + eventid + "' " + wheresql + " LIMIT " + start + "," + perpage);
            for (Map<String, Object> value : query) {
                Common.realname_set(sGlobal, sConfig, sNames, (Integer) value.get("uid"),
                        (String) value.get("username"), "", 0);
                tempS = (String) value.get("template");
                if (tempS != null) {
                    value.put("template", Common.nl2br(Common.htmlSpecialChars(tempS)));
                } else {
                    value.put("template", "");
                }
                count++;
            }
            List<Map<String, Object>> list = query;
            if (!Common.empty(key)) {
                if (list.size() > 0) {
                    status = String.valueOf(list.get(0).get("status"));
                } else {
                    status = "";
                }
            }
            String multi;
            try {
                multi = Common.smulti(sGlobal, start, perpage, count,
                        "cp.jsp?ac=event&op=members&id=" + eventid + "&status=" + status + "&key=" + key, null);
            } catch (Exception e) {
                return showMessage(request, response, e.getMessage());
            }
            request.setAttribute("status", status);
            request.setAttribute("list", list);
            request.setAttribute("multi", multi);
        } else if ("member".equals(op)) {
            Map<String, Object> supeUserEvent = (Map<String, Object>) sGlobal.get("supe_userevent");
            if (supeUserEvent == null || (Integer) supeUserEvent.get("status") < 3) {
                return showMessage(request, response, "no_privilege_manage_event_members");
            }
            try {
                if (submitCheck(request, "membersubmit")) {
                    String statusString = request.getParameter("status");
                    int status = Common.intval(statusString);
                    boolean rz;
                    String uid = request.getParameter("uid");
                    if (!Common.empty(uid)) {
                        Object object = verify_eventmembers(request, sGlobal, event, new String[] { uid },
                                statusString);
                        if (object instanceof MessageVO) {
                            return showMessage(request, response, (MessageVO) object);
                        }
                        rz = !Common.empty(object);
                    } else {
                        rz = false;
                    }
                    if (rz) {
                        String refer = request.getParameter("refer");
                        refer = Common.empty(refer)
                                ? "space.jsp?do=event&id=" + eventid + "&view=member&status=" + status
                                : refer;
                        return showMessage(request, response, "do_success", refer, 0);
                    } else {
                        return showMessage(request, response, "choose_right_eventmember");
                    }
                }
            } catch (Exception e) {
                return showMessage(request, response, e.getMessage());
            }
            int uid = Common.intval(request.getParameter("uid"));
            query = dataBaseService.executeQuery("SELECT * FROM " + JavaCenterHome.getTableName("userevent")
                    + " WHERE uid='" + uid + "' AND eventid='" + eventid + "'");
            Map<String, Object> userevent = query.size() > 0 ? query.get(0) : null;
            if (Common.empty(userevent)) {
                return showMessage(request, response, "choose_right_eventmember");
            }
            try {
                tempS = Common.nl2br(Common.getStr((String) userevent.get("template"), 255, true, false, true,
                        0, 0, request, response));
            } catch (Exception e) {
                return showMessage(request, response, e.getMessage());
            }
            userevent.put("template", tempS);
            request.setAttribute("uid", uid);
            request.setAttribute("userevent", userevent);
        } else if ("pic".equals(op)) {
            if (!allowmanage) {
                return showMessage(request, response, "no_privilege_manage_event_pic");
            }
            if (submitCheck(request, "deletepicsubmit")) {
                String[] ids = request.getParameterValues("ids[]");
                if (!Common.empty(ids)) {
                    dataBaseService.execute("DELETE FROM " + JavaCenterHome.getTableName("eventpic")
                            + " WHERE eventid='" + eventid + "' AND picid IN (" + Common.sImplode(ids) + ")");
                    dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("event")
                            + " SET picnum = (SELECT COUNT(*) FROM " + JavaCenterHome.getTableName("eventpic")
                            + " WHERE eventid='" + eventid + "') WHERE eventid = '" + eventid + "'");
                    return showMessage(request, response, "do_success", "cp.jsp?ac=event&op=pic&id=" + eventid,
                            0);
                } else {
                    return showMessage(request, response, "choose_event_pic");
                }
            }
            int perpage = 16;
            tempS = request.getParameter("page");
            int page = Common.empty(tempS) ? 1 : Common.intval(tempS);
            if (page < 1)
                page = 1;
            int start = (page - 1) * perpage;
            int maxPage = (Integer) sConfig.get("maxpage");
            if ((tempS = Common.ckStart(start, perpage, maxPage)) != null) {
                return showMessage(request, response, tempS);
            }
            String theurl = "cp.jsp?ac=event&id=" + eventid + "&op=pic";
            List<Map<String, Object>> photolist = null;
            int count = 0;
            query = dataBaseService.executeQuery("SELECT COUNT(*) AS cont FROM "
                    + JavaCenterHome.getTableName("eventpic") + " WHERE eventid = '" + eventid + "'");
            if (query.size() > 0) {
                count = (Integer) query.get(0).get("cont");
            }
            if (count != 0) {
                query = dataBaseService.executeQuery("SELECT pic.* FROM "
                        + JavaCenterHome.getTableName("eventpic") + " ep LEFT JOIN "
                        + JavaCenterHome.getTableName("pic") + " pic ON ep.picid=pic.picid WHERE ep.eventid='"
                        + eventid + "' ORDER BY ep.picid DESC LIMIT " + start + ", " + perpage);
                for (Map<String, Object> value : query) {
                    value.put("pic", Common.pic_get(sConfig, (String) value.get("filepath"),
                            (Integer) value.get("thumb"), (Integer) value.get("remote"), true));
                }
                photolist = query;
            }
            String multi = Common.multi(request, count, perpage, page, maxPage, theurl, null, null);
            int photolistSize = photolist == null ? 0 : photolist.size();
            request.setAttribute("photolistSize", photolistSize);
            request.setAttribute("photolist", photolist);
            request.setAttribute("multi", multi);
        } else if ("thread".equals(op)) {
            if (!allowmanage) {
                return showMessage(request, response, "no_privilege_manage_event_thread");
            }
            if (Common.empty(event.get("tagid"))) {
                return showMessage(request, response, "event_has_not_mtag");
            }
            try {
                if (submitCheck(request, "delthreadsubmit")) {
                    String[] ids = request.getParameterValues("ids[]");
                    if (!Common.empty(ids)) {
                        dataBaseService.execute("DELETE FROM " + JavaCenterHome.getTableName("thread")
                                + " WHERE eventid='" + eventid + "' AND tid IN (" + Common.sImplode(ids) + ")");
                        dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("event")
                                + " SET threadnum = (SELECT COUNT(*) FROM "
                                + JavaCenterHome.getTableName("thread") + " WHERE eventid='" + eventid
                                + "') WHERE eventid = '" + eventid + "'");
                        return showMessage(request, response, "do_success",
                                "cp.jsp?ac=event&id=" + eventid + "&op=thread", 0);
                    } else {
                        return showMessage(request, response, "choose_event_thread");
                    }
                }
            } catch (Exception e) {
                return showMessage(request, response, e.getMessage());
            }
            int perpage = 20;
            tempS = request.getParameter("page");
            int page = Common.empty(tempS) ? 1 : Common.intval(tempS);
            if (page < 1)
                page = 1;
            int start = (page - 1) * perpage;
            int maxPage = (Integer) sConfig.get("maxpage");
            if ((tempS = Common.ckStart(start, perpage, maxPage)) != null) {
                return showMessage(request, response, tempS);
            }
            List<Map<String, Object>> threadlist = null;
            int count = 0;
            query = dataBaseService.executeQuery("SELECT COUNT(*) AS cont FROM "
                    + JavaCenterHome.getTableName("thread") + " WHERE eventid = '" + eventid + "'");
            if (query.size() > 0) {
                count = (Integer) query.get(0).get("cont");
            }
            if (count != 0) {
                query = dataBaseService.executeQuery(
                        "SELECT * FROM " + JavaCenterHome.getTableName("thread") + " WHERE eventid='" + eventid
                                + "' ORDER BY lastpost DESC LIMIT " + start + ", " + perpage);
                for (Map<String, Object> value : query) {
                    Common.realname_set(sGlobal, sConfig, sNames, (Integer) value.get("uid"),
                            (String) value.get("username"), "", 0);
                    Common.realname_set(sGlobal, sConfig, sNames, (Integer) value.get("lastauthorid"),
                            (String) value.get("lastauthor"), "", 0);
                }
                threadlist = query;
            }
            String multi = Common.multi(request, count, perpage, page, maxPage,
                    "cp.jsp?ac=event&id=" + eventid + "&op=thread", null, null);
            request.setAttribute("threadlist", threadlist);
        } else if ("join".equals(op)) {
            boolean popupmenu_box;
            if (cpService.isBlackList((Integer) event.get("uid"), supe_uid) != 0) {
                popupmenu_box = true;
                return showMessage(request, response, "is_blacklist");
            }
            if (Common.empty(sGlobal.get("supe_userevent"))) {
                popupmenu_box = true;
                if (timestamp > (Integer) event.get("endtime")) {
                    return showMessage(request, response, "event_is_over");
                }
                if (timestamp > (Integer) event.get("deadline")) {
                    return showMessage(request, response, "event_meet_deadline");
                }
                if ((Integer) event.get("limitnum") > 0
                        && (Integer) event.get("membernum") >= (Integer) event.get("limitnum")) {
                    return showMessage(request, response, "event_already_full");
                }
                if ((Integer) event.get("public") < 2) {
                    query = dataBaseService.executeQuery(
                            "SELECT * FROM " + JavaCenterHome.getTableName("eventinvite") + " WHERE eventid = '"
                                    + event.get("eventid") + "' AND touid = '" + supe_uid + "' LIMIT 1");
                    Map<String, Object> value = query.size() > 0 ? query.get(0) : null;
                    if (Common.empty(value)) {
                        return showMessage(request, response, "event_join_limit");
                    }
                }
            }
            if (submitCheck(request, "joinsubmit")) {
                Map<String, Object> supe_userevent = (Map<String, Object>) sGlobal.get("supe_userevent");
                boolean supe_usereventNotEmpty = !Common.empty(supe_userevent);
                Integer supe_usereventStatus = supe_usereventNotEmpty ? (Integer) supe_userevent.get("status")
                        : null;
                if (supe_usereventStatus != null && supe_usereventStatus == 0) {
                    Map<String, Object> arr = new HashMap<String, Object>();
                    tempS = request.getParameter("fellow");
                    if (tempS != null) {
                        arr.put("fellow", Common.intval(tempS));
                    }
                    tempS = request.getParameter("template");
                    if (!Common.empty(tempS)) {
                        try {
                            tempS = Common.getStr(tempS, 255, true, true, true, 0, 0, request, response);
                        } catch (Exception e) {
                            return showMessage(request, response, e.getMessage());
                        }
                        arr.put("template", tempS);
                    }
                    if (!Common.empty(arr)) {
                        Map<String, Object> whereData = new HashMap<String, Object>();
                        whereData.put("eventid", eventid);
                        whereData.put("uid", supe_uid);
                        dataBaseService.updateTable("userevent", arr, whereData);
                    }
                    return showMessage(request, response, "do_success", "space.jsp?do=event&id=" + eventid, 2);
                }
                if (supe_usereventStatus != null && supe_usereventStatus > 1) {
                    Map<String, Object> arr = new HashMap<String, Object>();
                    int num = 0;
                    tempS = request.getParameter("fellow");
                    if (tempS != null) {
                        int fellow = Common.intval(tempS);
                        arr.put("fellow", fellow);
                        Integer supe_usereventFellow = (Integer) supe_userevent.get("fellow");
                        supe_usereventFellow = supe_usereventFellow == null ? 0 : supe_usereventFellow;
                        num = fellow - supe_usereventFellow;
                        int eventLimitnum = (Integer) event.get("limitnum");
                        if (eventLimitnum > 0 && num + (Integer) event.get("membernum") > eventLimitnum) {
                            return showMessage(request, response, "event_already_full");
                        }
                    }
                    tempS = request.getParameter("template");
                    if (!Common.empty(tempS)) {
                        arr.put("template", tempS);
                    }
                    if (!Common.empty(arr)) {
                        Map<String, Object> whereData = new HashMap<String, Object>();
                        whereData.put("eventid", eventid);
                        whereData.put("uid", supe_uid);
                        dataBaseService.updateTable("userevent", arr, whereData);
                    }
                    if (num != 0) {
                        dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("event")
                                + " SET membernum = membernum + " + num + " WHERE eventid=" + eventid);
                    }
                    return showMessage(request, response, "do_success", "space.jsp?do=event&id=" + eventid, 0);
                }
                int arrStatus = 2;
                Map<String, Object> arr = new HashMap<String, Object>();
                arr.put("eventid", eventid);
                arr.put("uid", supe_uid);
                arr.put("username", supe_username);
                arr.put("template", event.get("template"));
                arr.put("fellow", 0);
                arr.put("dateline", timestamp);
                int num = 1;
                String numsql;
                tempS = request.getParameter("fellow");
                if (!Common.empty(tempS)) {
                    int fellow = Common.intval(tempS);
                    arr.put("fellow", fellow);
                    num += fellow;
                }
                tempS = request.getParameter("template");
                if (!Common.empty(tempS)) {
                    try {
                        tempS = Common.getStr(tempS, 255, true, true, true, 0, 0, request, response);
                    } catch (Exception e) {
                        return showMessage(request, response, e.getMessage());
                    }
                    arr.put("template", tempS);
                }
                int eventLimitnum = (Integer) event.get("limitnum");
                if (eventLimitnum > 0 && num + (Integer) event.get("membernum") > eventLimitnum) {
                    return showMessage(request, response, "event_will_full");
                }
                numsql = " membernum = membernum + " + num + " ";
                query = dataBaseService
                        .executeQuery("SELECT * FROM " + JavaCenterHome.getTableName("eventinvite")
                                + " WHERE eventid='" + eventid + "' AND touid='" + supe_uid + "'");
                Map<String, Object> eventinvite = query.size() > 0 ? query.get(0) : null;
                if (!Common.empty(event.get("verify")) && Common.empty(eventinvite)) {
                    arrStatus = 0;
                }
                arr.put("status", arrStatus);
                if (supe_usereventStatus != null && supe_usereventStatus == 1) {
                    Map<String, Object> whereData = new HashMap<String, Object>();
                    whereData.put("uid", supe_uid);
                    whereData.put("eventid", eventid);
                    dataBaseService.updateTable("userevent", arr, whereData);
                    numsql += ",follownum = follownum - 1 ";
                } else {
                    dataBaseService.insertTable("userevent", arr, false, false);
                }
                int eventUid = (Integer) event.get("uid");
                if (arrStatus == 2) {
                    dataBaseService.execute("UPDATE " + JavaCenterHome.getTableName("event") + " SET " + numsql
                            + " WHERE eventid = '" + eventid + "'");
                    if (Common.ckPrivacy(sGlobal, sConfig, space, "join", 0)) {
                        Common.realname_set(sGlobal, sConfig, sNames, eventUid, (String) event.get("username"),
                                "", 0);
                        Common.realname_get(sGlobal, sConfig, sNames, space);
                        Map<String, Object> title_data = new HashMap<String, Object>();
                        title_data.put("title", event.get("title"));
                        title_data.put("eventid", event.get("eventid"));
                        title_data.put("uid", eventUid);
                        title_data.put("username", sNames.get(eventUid));
                        cpService.addFeed(sGlobal, "event", Common.getMessage(request, "cp_event_join"),
                                title_data, "", null, "", null, null, "", 0, 0, 0, "", false);
                    }
                } else if (arrStatus == 0) {
                    if (supe_usereventStatus != null && supe_usereventStatus == 1) {
                        dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("event")
                                + " SET follownum = follownum - 1 WHERE eventid = '" + eventid + "'");
                    }
                    List<Integer> note_ids = new ArrayList<Integer>();
                    List<String> note_inserts = new ArrayList<String>();
                    int eventEventid = (Integer) event.get("eventid");
                    String note_msg = Common.getMessage(request, "cp_event_join_verify",
                            "space.jsp?do=event&id=" + eventEventid, event.get("title"),
                            "cp.jsp?ac=event&id=" + eventEventid + "&op=members&status=0&key=" + supe_username);
                    query = dataBaseService.executeQuery("SELECT ue.*, sf.* FROM "
                            + JavaCenterHome.getTableName("userevent") + " ue LEFT JOIN "
                            + JavaCenterHome.getTableName("spacefield")
                            + " sf ON ue.uid=sf.uid WHERE ue.eventid='" + eventid + "' AND ue.status >= 3");
                    Map<String, Object> privacyM;
                    Set<String> filter;
                    Map<String, Object> filter_noteM;
                    Map<String, Object> note = new HashMap<String, Object>();
                    note.put("type", "eventmember");
                    note.put("authorid", supe_uid);
                    StringBuilder builder = new StringBuilder();
                    int valueUid;
                    for (Map<String, Object> value : query) {
                        tempS = (String) value.get("privacy");
                        privacyM = Common.empty(tempS) ? new HashMap<String, Object>()
                                : (Map<String, Object>) Serializer.unserialize(tempS);
                        value.put("privacy", privacyM);
                        filter_noteM = (Map<String, Object>) privacyM.get("filter_note");
                        filter = Common.empty(filter_noteM) ? new HashSet<String>() : filter_noteM.keySet();
                        if (cpService.checkNoteUid(note, filter)) {
                            valueUid = (Integer) value.get("uid");
                            note_ids.add(valueUid);
                            builder.append("('");
                            builder.append(valueUid);
                            builder.append("', 'eventmember', '1', '");
                            builder.append(supe_uid);
                            builder.append("', '");
                            builder.append(supe_username);
                            builder.append("', '");
                            builder.append(Common.addSlashes(note_msg));
                            builder.append("', '");
                            builder.append(timestamp);
                            builder.append("')");
                            note_inserts.add(builder.toString());
                            builder.delete(0, builder.length());
                        }
                    }
                    if (!Common.empty(note_inserts)) {
                        dataBaseService.execute("INSERT INTO " + JavaCenterHome.getTableName("notification")
                                + " (`uid`, `type`, `new`, `authorid`, `author`, `note`, `dateline`) VALUES "
                                + Common.implode(note_inserts, ","));
                        dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("space")
                                + " SET notenum=notenum+1 WHERE uid IN (" + Common.sImplode(note_ids) + ")");
                    }
                    try {
                        cpService.sendMail(request, response, eventUid, "",
                                Common.getMessage(request, "event_application"), note_msg, "event");
                    } catch (Exception e) {
                        return showMessage(request, response, e.getMessage());
                    }
                }
                Common.getReward("joinevent", true, 0, eventid + "", true, request, response);
                cpService.updateStat(request, "eventjoin", false);
                if (!Common.empty(eventinvite)) {
                    dataBaseService.execute("DELETE FROM " + JavaCenterHome.getTableName("eventinvite")
                            + " WHERE eventid='" + eventid + "' AND touid='" + supe_uid + "'");
                    dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("space")
                            + " SET eventinvitenum=eventinvitenum-1 WHERE uid = '" + supe_uid
                            + "' AND eventinvitenum>0");
                }
                return showMessage(request, response, "do_success", "space.jsp?do=event&id=" + eventid, 0);
            }
        } else if ("quit".equals(op)) {
            if (eventid == 0) {
                return showMessage(request, response, "event_does_not_exist");
            }
            if (submitCheck(request, "quitsubmit")) {
                String tourl = "space.jsp?do=event&id=" + eventid;
                int uid = supe_uid;
                Map<String, Object> userevent = (Map<String, Object>) sGlobal.get("supe_userevent");
                if (!Common.empty(userevent) && (Integer) event.get("uid") != uid) {
                    dataBaseService.execute("DELETE FROM " + JavaCenterHome.getTableName("userevent")
                            + " WHERE eventid='" + eventid + "' AND uid='" + uid + "'");
                    if ((Integer) userevent.get("status") >= 2) {
                        int num = 1 + (Integer) userevent.get("fellow");
                        dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("event")
                                + " SET membernum = membernum - " + num + " WHERE eventid='" + eventid + "'");
                    }
                    return showMessage(request, response, "do_success", tourl, 0);
                } else {
                    return showMessage(request, response, "cannot_quit_event", tourl, 2);
                }
            }
        } else if ("follow".equals(op)) {
            if (eventid == 0) {
                return showMessage(request, response, "event_does_not_exist");
            }
            Map<String, Object> supe_userevent = (Map<String, Object>) sGlobal.get("supe_userevent");
            boolean popupmenu_box = false;
            if (!Common.empty(supe_userevent)) {
                popupmenu_box = true;
                if ((Integer) supe_userevent.get("status") <= 1) {
                    return showMessage(request, response, "event_has_followed");
                } else {
                    return showMessage(request, response, "event_has_joint");
                }
            }
            if (submitCheck(request, "followsubmit")) {
                Map<String, Object> arr = new HashMap<String, Object>();
                arr.put("eventid", eventid);
                arr.put("uid", supe_uid);
                arr.put("username", supe_username);
                arr.put("status", 1);
                arr.put("fellow", 0);
                arr.put("template", event.get("template"));
                dataBaseService.insertTable("userevent", arr, false, false);
                dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("event")
                        + " SET follownum = follownum + 1 WHERE eventid='" + eventid + "'");
                return showMessage(request, response, "do_success", "space.jsp?do=event&id=" + eventid, 0);
            }
        } else if ("cancelfollow".equals(op)) {
            if (eventid == 0) {
                return showMessage(request, response, "event_does_not_exist");
            }
            if (submitCheck(request, "cancelfollowsubmit")) {
                Map<String, Object> supe_userevent = (Map<String, Object>) sGlobal.get("supe_userevent");
                if (!Common.empty(supe_userevent) && (Integer) supe_userevent.get("status") == 1) {
                    dataBaseService.execute("DELETE FROM " + JavaCenterHome.getTableName("userevent")
                            + " WHERE uid='" + supe_uid + "' AND eventid='" + eventid + "'");
                    dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("event")
                            + " SET follownum = follownum - 1 WHERE eventid='" + eventid + "'");
                }
                return showMessage(request, response, "do_success", "space.jsp?do=event&id=" + eventid, 0);
            }
        } else if ("eventinvite".equals(op)) {
            if (!Common.empty(request.getParameter("r"))) {
                tempS = request.getParameter("page");
                String tourl = "cp.jsp?ac=event&op=eventinvite"
                        + (tempS != null ? "&page=" + Common.intval(tempS) : "");
                if (eventid != 0) {
                    dataBaseService.execute("DELETE FROM " + JavaCenterHome.getTableName("eventinvite")
                            + " WHERE eventid = '" + eventid + "' AND touid = '" + supe_uid + "'");
                    dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("space")
                            + " SET eventinvitenum=eventinvitenum-1 WHERE uid = '" + supe_uid
                            + "' AND eventinvitenum>0");
                } else {
                    dataBaseService.execute("DELETE FROM " + JavaCenterHome.getTableName("eventinvite")
                            + " WHERE touid = '" + supe_uid + "'");
                    dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("space")
                            + " SET eventinvitenum=0 WHERE uid = '" + supe_uid + "'");
                }
                return showMessage(request, response, "do_success", tourl, 0);
            }
            int perpage = 20;
            tempS = request.getParameter("page");
            int page = Common.empty(tempS) ? 1 : Common.intval(tempS);
            if (page < 1)
                page = 1;
            int start = (page - 1) * perpage;
            int maxPage = (Integer) sConfig.get("maxpage");
            if ((tempS = Common.ckStart(start, perpage, maxPage)) != null) {
                return showMessage(request, response, tempS);
            }
            String theurl = "cp.jsp?ac=event&op=eventinvite";
            Map<String, Object> whereArr = new HashMap<String, Object>();
            whereArr.put("touid", supe_uid);
            int count = Common.intval(Common.getCount("eventinvite", whereArr, null));
            if (count != (Integer) space.get("eventinvitenum")) {
                Map<String, Object> setData = new HashMap<String, Object>();
                setData.put("eventinvitenum", count);
                Map<String, Object> whereData = new HashMap<String, Object>();
                whereData.put("uid", space.get("uid"));
                dataBaseService.updateTable("space", setData, whereData);
            }
            List<Map<String, Object>> eventinvites = null;
            if (count > 0) {
                query = dataBaseService.executeQuery("SELECT ei.*, e.*, ei.dateline as invitetime FROM "
                        + JavaCenterHome.getTableName("eventinvite") + " ei LEFT JOIN "
                        + JavaCenterHome.getTableName("event") + " e ON ei.eventid=e.eventid WHERE ei.touid='"
                        + supe_uid + "' limit " + start + ", " + perpage);
                for (Map<String, Object> value : query) {
                    Common.realname_set(sGlobal, sConfig, sNames, (Integer) value.get("uid"),
                            (String) value.get("username"), "", 0);
                    if (!Common.empty(value.get("poster"))) {
                        value.put("pic", Common.pic_get(sConfig, (String) value.get("poster"),
                                (Integer) value.get("thumb"), (Integer) value.get("remote"), true));
                    } else {
                        value.put("pic", globalEventClass.get(value.get("classid")).get("poster"));
                    }
                }
                eventinvites = query;
            }
            String multi = Common.multi(request, count, perpage, page, maxPage, theurl, null, null);
            request.setAttribute("eventinvites", eventinvites);
            request.setAttribute("multi", multi);
        } else if ("acceptinvite".equals(op)) {
            if (eventid == 0) {
                return showMessage(request, response, "event_does_not_exist");
            }
            query = dataBaseService.executeQuery("SELECT * FROM " + JavaCenterHome.getTableName("eventinvite")
                    + " WHERE eventid='" + eventid + "' AND touid='" + supe_uid + "' LIMIT 1");
            Map<String, Object> eventinvite = query.size() > 0 ? query.get(0) : null;
            if (Common.empty(eventinvite)) {
                return showMessage(request, response, "eventinvite_does_not_exist");
            }
            dataBaseService.execute("DELETE FROM " + JavaCenterHome.getTableName("eventinvite")
                    + " WHERE eventid='" + eventid + "' AND touid='" + supe_uid + "'");
            dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("space")
                    + " SET eventinvitenum=eventinvitenum-1 WHERE uid = '" + supe_uid
                    + "' AND eventinvitenum>0");
            if (cpService.isBlackList((Integer) event.get("uid"), supe_uid) != 0) {
                return showMessage(request, response, "is_blacklist");
            }
            if (timestamp > (Integer) event.get("endtime")) {
                return showMessage(request, response, "event_is_over");
            }
            if (timestamp > (Integer) event.get("deadline")) {
                return showMessage(request, response, "event_meet_deadline");
            }
            int eventLimitnum = (Integer) event.get("limitnum");
            int eventMembernum = (Integer) event.get("membernum");
            if (eventLimitnum > 0 && eventMembernum >= eventLimitnum) {
                return showMessage(request, response, "event_already_full");
            }
            String numsql = "membernum = membernum + 1";
            Map<String, Object> supe_userevent = (Map<String, Object>) sGlobal.get("supe_userevent");
            if (Common.empty(supe_userevent)) {
                Map<String, Object> arr = new HashMap<String, Object>();
                arr.put("eventid", eventid);
                arr.put("uid", supe_uid);
                arr.put("username", supe_username);
                arr.put("status", 2);
                arr.put("template", event.get("template"));
                arr.put("fellow", 0);
                arr.put("dateline", timestamp);
                dataBaseService.insertTable("userevent", arr, false, false);
                dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("event") + " SET "
                        + numsql + " WHERE eventid = '" + eventid + "'");
                if (Common.ckPrivacy(sGlobal, sConfig, space, "join", 0)) {
                    int eventUid = (Integer) event.get("uid");
                    Common.realname_set(sGlobal, sConfig, sNames, (Integer) eventUid,
                            (String) event.get("username"), "", 0);
                    Common.realname_get(sGlobal, sConfig, sNames, space);
                    Map<String, Object> title_data = new HashMap<String, Object>();
                    title_data.put("title", event.get("title"));
                    title_data.put("eventid", event.get("eventid"));
                    title_data.put("uid", eventUid);
                    title_data.put("username", sNames.get(eventUid));
                    cpService.addFeed(sGlobal, "event", Common.getMessage(request, "cp_event_join"), title_data,
                            "", null, "", null, null, "", 0, 0, 0, "", false);
                }
            } else if ((Integer) supe_userevent.get("status") < 2) {
                Map<String, Object> arr = new HashMap<String, Object>();
                arr.put("status", 2);
                if ((Integer) supe_userevent.get("status") == 1) {
                    numsql += ",follownum = follownum - 1 ";
                }
                if (eventLimitnum > 0
                        && eventMembernum + (Integer) supe_userevent.get("fellow") > eventLimitnum) {
                    arr.put("fellow", 0);
                }
                Map<String, Object> whereData = new HashMap<String, Object>();
                whereData.put("uid", supe_uid);
                whereData.put("eventid", eventid);
                dataBaseService.updateTable("userevent", arr, whereData);
                dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("event") + " SET "
                        + numsql + " WHERE eventid = '" + eventid + "'");
                if (Common.ckPrivacy(sGlobal, sConfig, space, "join", 0)) {
                    int eventUid = (Integer) event.get("uid");
                    Map<String, Object> title_data = new HashMap<String, Object>();
                    title_data.put("title", event.get("title"));
                    title_data.put("eventid", event.get("eventid"));
                    title_data.put("uid", eventUid);
                    title_data.put("username", event.get("username"));
                    cpService.addFeed(sGlobal, "event", Common.getMessage(request, "cp_event_join"), title_data,
                            "", null, "", null, null, "", 0, 0, 0, "", false);
                }
            }
            return showMessage(request, response, Common.getMessage(request, "cp_event_accept_success",
                    "space.jsp?do=event&id=" + event.get("eventid")));
        } else if ("delete".equals(op)) {
            if (eventid == 0) {
                return showMessage(request, response, "event_does_not_exist");
            }
            if (!allowmanage) {
                return showMessage(request, response, "no_privilege");
            }
            if (submitCheck(request, "deletesubmit")) {
                adminDeleteService.deleteEvents(request, response, sGlobal, new Integer[] { eventid });
                return showMessage(request, response, "do_success", "space.jsp?do=event", 2);
            }
        } else if ("print".equals(op)) {
            if (eventid == 0) {
                return showMessage(request, response, "event_does_not_exist");
            }
            if (submitCheck(request, "printsubmit")) {
                List<Map<String, Object>> members;
                List uid;
                if (!Common.empty(request.getParameter("admin"))) {
                    query = dataBaseService.executeQuery(
                            "SELECT * FROM " + JavaCenterHome.getTableName("userevent") + " WHERE eventid='"
                                    + eventid + "' AND status > 1 ORDER BY status DESC, dateline ASC");
                } else {
                    query = dataBaseService
                            .executeQuery("SELECT * FROM " + JavaCenterHome.getTableName("userevent")
                                    + " WHERE eventid='" + eventid + "' AND status = 2 ORDER BY dateline ASC");
                }
                for (Map<String, Object> value : query) {
                    value.put("template",
                            Common.nl2br(Common.htmlSpecialChars((String) value.get("template"))));
                    Common.realname_set(sGlobal, sConfig, sNames, (Integer) value.get("uid"),
                            (String) value.get("username"), "", 0);
                }
                members = query;
                Common.realname_get(sGlobal, sConfig, sNames, space);
                request.setAttribute("event", event);
                request.setAttribute("members", members);
                return include(request, response, sConfig, sGlobal, "cp_event_sheet.jsp");
            }
        } else if ("close".equals(op)) {
            if (eventid == 0) {
                return showMessage(request, response, "event_does_not_exist");
            }
            if (!allowmanage) {
                return showMessage(request, response, "no_privilege");
            }
            if ((Integer) event.get("grade") < 1 || (Integer) event.get("endtime") > timestamp) {
                return showMessage(request, response, "event_can_not_be_closed");
            }
            if (submitCheck(request, "closesubmit")) {
                Map<String, Object> setData = new HashMap<String, Object>();
                setData.put("grade", -2);
                Map<String, Object> whereData = new HashMap<String, Object>();
                whereData.put("eventid", eventid);
                dataBaseService.updateTable("event", setData, whereData);
                return showMessage(request, response, "do_success", "space.jsp?do=event&id=" + eventid, 0);
            }
        } else if ("open".equals(op)) {
            if (eventid == 0) {
                return showMessage(request, response, "event_does_not_exist");
            }
            if (!allowmanage) {
                return showMessage(request, response, "no_privilege");
            }
            if ((Integer) event.get("grade") != -2 || (Integer) event.get("endtime") > timestamp) {
                return showMessage(request, response, "event_can_not_be_opened");
            }
            if (submitCheck(request, "opensubmit")) {
                Map<String, Object> setData = new HashMap<String, Object>();
                setData.put("grade", 1);
                Map<String, Object> whereData = new HashMap<String, Object>();
                whereData.put("eventid", eventid);
                dataBaseService.updateTable("event", setData, whereData);
                return showMessage(request, response, "do_success", "space.jsp?do=event&id=" + eventid, 0);
            }
        } else if ("calendar".equals(op)) {
            List<String> match = null;
            String monthGet = request.getParameter("month");
            String dateGet = request.getParameter("date");
            if (Common.empty(monthGet)) {
                match = Common.pregMatch(dateGet, "^(\\d{4}-\\d{1,2})");
                if (!Common.empty(match)) {
                    monthGet = match.get(1);
                }
            }
            if (monthGet != null) {
                match = Common.pregMatch(monthGet, "^(\\d{4})-(\\d{1,2})$");
            }
            int year;
            int month;
            if (!Common.empty(match)) {
                year = Common.intval(match.get(1));
                month = Common.intval(match.get(2));
            } else {
                year = Common.intval(Common.sgmdate(request, "yyyy", timestamp));
                month = Common.intval(Common.sgmdate(request, "MM", timestamp));
            }
            String nextmonth;
            String premonth;
            if (month == 12) {
                nextmonth = (year + 1) + "-" + "1";
                premonth = year + "-11";
            } else if (month == 1) {
                nextmonth = year + "-2";
                premonth = (year - 1) + "-12";
            } else {
                nextmonth = year + "-" + (month + 1);
                premonth = year + "-" + (month - 1);
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MONTH, month - 1);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.YEAR, year);
            int daystart = (int) (calendar.getTimeInMillis() / 1000);
            int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            int dayscount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            calendar.add(Calendar.MONTH, 1);
            int dayend = (int) (calendar.getTimeInMillis() / 1000);
            Map<Integer, Map<String, Object>> days = new LinkedHashMap<Integer, Map<String, Object>>();
            Map<String, Object> subM;
            for (int i = 1; i <= dayscount; i++) {
                subM = new HashMap<String, Object>();
                subM.put("count", 0);
                subM.put("events", new ArrayList<Map<String, Object>>());
                subM.put("class", "");
                days.put(i, subM);
            }
            query = dataBaseService.executeQuery(
                    "SELECT * FROM " + JavaCenterHome.getTableName("event") + " WHERE starttime < " + dayend
                            + " AND endtime > " + daystart + " ORDER BY eventid DESC LIMIT 100");
            int tempInt;
            int start;
            int end;
            List<Map<String, Object>> subList;
            for (Map<String, Object> value : query) {
                if ((Integer) value.get("public") < 1 || (tempInt = (Integer) value.get("grade")) == 0
                        || tempInt == -1) {
                    continue;
                }
                tempInt = (Integer) value.get("starttime");
                if (tempInt < daystart) {
                    start = 1;
                } else {
                    calendar.setTimeInMillis(tempInt * 1000L);
                    start = calendar.get(Calendar.DAY_OF_MONTH);
                }
                tempInt = (Integer) value.get("endtime");
                if (tempInt > dayend) {
                    end = dayscount;
                } else {
                    calendar.setTimeInMillis(tempInt * 1000L);
                    end = calendar.get(Calendar.DAY_OF_MONTH);
                }
                for (int i = start; i <= end; i++) {
                    subM = days.get(i);
                    tempInt = (Integer) subM.get("count");
                    if (tempInt < 10) {
                        subList = (List<Map<String, Object>>) subM.get("events");
                        subList.add(value);
                        subM.put("count", tempInt + 1);
                        subM.put("class", " on_link");
                    }
                }
            }
            int d = 0;
            if (month == Common.intval(Common.sgmdate(request, "MM", timestamp))
                    && year == Common.intval(Common.sgmdate(request, "yyyy", timestamp))) {
                d = Common.intval(Common.sgmdate(request, "dd", timestamp));
                subM = days.get(d);
                subM.put("class", "on_today");
            }
            if (!Common.empty(dateGet)) {
                int t = Common.strToTime(dateGet, Common.getTimeOffset(sGlobal, sConfig));
                if (month == Common.intval(Common.sgmdate(request, "MM", t))
                        && year == Common.intval(Common.sgmdate(request, "yyyy", t))) {
                    d = Common.intval(Common.sgmdate(request, "dd", t));
                    subM = days.get(d);
                    subM.put("class", "on_select");
                }
            }
            String url = request.getParameter("url");
            url = !Common.empty(url) ? url.replaceAll("date=[\\d\\-]+", "") : "space.jsp?do=event";
            request.setAttribute("premonth", premonth);
            request.setAttribute("nextmonth", nextmonth);
            request.setAttribute("year", year);
            request.setAttribute("month", month);
            request.setAttribute("week", week);
            request.setAttribute("days", days);
            request.setAttribute("url", url);
        } else if ("edithot".equals(op)) {
            if (!Common.checkPerm(request, response, "manageevent")) {
                return showMessage(request, response, "no_privilege");
            }
            if (submitCheck(request, "hotsubmit")) {
                int hot = Common.intval(request.getParameter("hot"));
                Map<String, Object> setData = new HashMap<String, Object>();
                setData.put("hot", hot);
                Map<String, Object> whereData = new HashMap<String, Object>();
                whereData.put("eventid", eventid);
                dataBaseService.updateTable("event", setData, whereData);
                if (hot > 0) {
                    feedService.feedPublish(request, response, eventid, "eventid", false);
                } else {
                    whereData.clear();
                    whereData.put("id", eventid);
                    whereData.put("idtype", eventid);
                    dataBaseService.updateTable("feed", setData, whereData);
                }
                return showMessage(request, response, "do_success",
                        "space.jsp?uid=" + event.get("uid") + "&do=event&id=" + eventid, 0);
            }
        } else if ("edit".equals(op)) {
            if (eventid != 0) {
                if (!allowmanage) {
                    return showMessage(request, response, "no_privilege_edit_event");
                }
            } else {
                if (!Common.checkPerm(request, response, "allowevent")) {
                    return showMessage(request, response, "no_privilege_add_event");
                }
                if (!cpService.checkRealName(request, "event")) {
                    return showMessage(request, response, "no_privilege_realname");
                }
                if (!cpService.checkVideoPhoto(request, response, "event")) {
                    return showMessage(request, response, "no_privilege_videophoto");
                }
                switch (cpService.checkNewUser(request, response)) {
                case 1:
                    break;
                case 2:
                    return showMessage(request, response, "no_privilege_newusertime", "", 1,
                            String.valueOf(sConfig.get("newusertime")));
                case 3:
                    return showMessage(request, response, "no_privilege_avatar");
                case 4:
                    return showMessage(request, response, "no_privilege_friendnum", "", 1,
                            String.valueOf(sConfig.get("need_friendnum")));
                case 5:
                    return showMessage(request, response, "no_privilege_email");
                }
                event = new HashMap<String, Object>();
                event.put("eventid", "");
                int starttime = (int) (Math.ceil(timestamp / 3600D) * 3600 + 7200);
                event.put("starttime", starttime);
                event.put("endtime", starttime + 14400);
                event.put("deadline", starttime);
                event.put("allowinvite", 1);
                event.put("allowpost", 1);
                event.put("allowpic", 1);
                event.put("allowfellow", 0);
                event.put("verify", 0);
                event.put("public", 2);
                event.put("limitnum", 0);
                event.put("province", space.get("resideprovince"));
                event.put("city", space.get("residecity"));
                Map<String, Object> topic = null;
                int topicid = Common.intval(request.getParameter("topicid"));
                if (topicid != 0) {
                    topic = Common.getTopic(request, topicid);
                }
                Map<String, String> actives = null;
                if (!Common.empty(topic)) {
                    actives = new HashMap<String, String>();
                    actives.put("event", " class=\"active\"");
                }
                request.setAttribute("topicid", topicid);
                request.setAttribute("topic", topic);
            }
            List<Map<String, Object>> mtags = null;
            Integer eventUid = (Integer) event.get("uid");
            if (eventid == 0 || (eventUid != null && eventUid.intValue() == supe_uid)) {
                query = dataBaseService.executeQuery("SELECT mtag.* FROM "
                        + JavaCenterHome.getTableName("tagspace") + " st LEFT JOIN "
                        + JavaCenterHome.getTableName("mtag") + " mtag ON st.tagid=mtag.tagid WHERE st.uid='"
                        + supe_uid + "' AND st.grade=9");
                mtags = query;
            }
            int tagid = Common.intval(request.getParameter("tagid"));
            if (tagid != 0 && Common.empty(event.get("tagid"))) {
                event.put("tagid", tagid);
            }
            Map<String, Object> subM;
            Object tempOb;
            for (Entry<Integer, Map<String, Object>> entry : globalEventClass.entrySet()) {
                subM = entry.getValue();
                tempOb = subM.get("template");
                if (tempOb != null) {
                    subM.put("template", String.valueOf(tempOb).replace("\r\n", "<br>").replace("\r", "<br>")
                            .replace("\n", "<br>"));
                }
            }
            request.setAttribute("globalEventClass", globalEventClass);
            request.setAttribute("mtags", mtags);
            request.setAttribute("ckPrivacy", Common.ckPrivacy(sGlobal, sConfig, space, "event", 1));
        }
    } catch (Exception e) {
        return showMessage(request, response, e.getMessage());
    }
    Common.realname_get(sGlobal, sConfig, sNames, space);
    request.setAttribute("op", op);
    request.setAttribute("eventid", eventid);
    request.setAttribute("allowmanage", allowmanage);
    request.setAttribute("event", event);
    request.setAttribute("menus", menus);
    return include(request, response, sConfig, sGlobal, "cp_event.jsp");
}

From source file:org.openbravo.test.costing.TestCosting.java

@SuppressWarnings("unchecked")
private void assertDocumentPost(BaseOBObject document, String productId,
        List<DocumentPostAssert> documentPostAssertList) {
    try {//from  w ww.j a v a2  s  .c om

        BaseOBObject doc = OBDal.getInstance().get(document.getClass(), document.getId());
        if (!doc.get("posted").equals("Y")) {
            OBDal.getInstance().refresh(doc);
            Thread.sleep(5000);
            for (int i = 0; i < 10 && !doc.get("posted").equals("Y"); i++) {
                postDocument(doc);
                doc = OBDal.getInstance().get(doc.getClass(), doc.getId());
                OBDal.getInstance().refresh(doc);
                Thread.sleep(1000);
            }
        }

        assertEquals(doc.get("posted"), "Y");

        final OBCriteria<Table> criteria1 = OBDal.getInstance().createCriteria(Table.class);
        criteria1.add(Restrictions.eq(Table.PROPERTY_NAME, doc.getEntityName()));
        Table table = criteria1.list().get(0);

        final OBCriteria<AccountingFact> criteria2 = OBDal.getInstance().createCriteria(AccountingFact.class);
        criteria2.add(Restrictions.eq(AccountingFact.PROPERTY_RECORDID, doc.getId()));
        criteria2.add(Restrictions.eq(AccountingFact.PROPERTY_TABLE, table));
        criteria2.addOrderBy(AccountingFact.PROPERTY_SEQUENCENUMBER, true);
        String groupId = criteria2.list().get(0).getGroupID();

        assertEquals(criteria2.list().size(), documentPostAssertList.size());

        int i = 0;
        for (AccountingFact accountingFact : criteria2.list()) {

            String lineListProperty = Character.toLowerCase(doc.getEntityName().charAt(0))
                    + doc.getEntityName().substring(1) + "LineList";

            BaseOBObject line = null;
            if (doc.getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME)) {
                if (i % 2 == 0) {
                    line = ((ReceiptInvoiceMatch) doc).getGoodsShipmentLine();
                } else {
                    line = ((ReceiptInvoiceMatch) doc).getInvoiceLine();
                }
            } else if (doc.getEntityName().equals(ProductionTransaction.ENTITY_NAME)) {
                StringBuffer where = new StringBuffer();
                where.append(" as t1 ");
                where.append("\n left join t1." + ProductionLine.PROPERTY_PRODUCTIONPLAN + " t2");
                where.append("\n where t2." + ProductionPlan.PROPERTY_PRODUCTION + " = :productionTransaction");
                where.append("\n order by t1." + ProductionLine.PROPERTY_LINENO);
                OBQuery<ProductionLine> hql = OBDal.getInstance().createQuery(ProductionLine.class,
                        where.toString());
                hql.setNamedParameter("productionTransaction",
                        OBDal.getInstance().get(ProductionTransaction.class, doc.getId()));
                line = hql.list().get(i / 2);
            } else if (doc.getEntityName().equals(CostAdjustment.ENTITY_NAME)) {
                final OBCriteria<CostAdjustmentLine> criteria3 = OBDal.getInstance()
                        .createCriteria(CostAdjustmentLine.class);
                criteria3.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_COSTADJUSTMENT, doc));
                criteria3.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_NEEDSPOSTING, true));
                criteria3.addOrderBy(CostAdjustmentLine.PROPERTY_LINENO, true);
                line = criteria3.list().get(i / 2);
            } else if (productId != null && (productId.equals(LANDEDCOSTTYPE1_ID)
                    || productId.equals(LANDEDCOSTTYPE2_ID) || productId.equals(LANDEDCOSTTYPE3_ID))) {
                line = ((List<BaseOBObject>) OBDal.getInstance().get(doc.getClass(), doc.getId())
                        .get(lineListProperty)).get(0);
            } else if (doc.getEntityName().equals(LandedCost.ENTITY_NAME)) {
                StringBuffer where = new StringBuffer();
                where.append(" as t1 ");
                where.append("\n join t1." + LCReceiptLineAmt.PROPERTY_LANDEDCOSTRECEIPT + " t2");
                where.append("\n join t1." + LCReceiptLineAmt.PROPERTY_LANDEDCOSTCOST + " t3");
                where.append("\n join t1." + LCReceiptLineAmt.PROPERTY_GOODSSHIPMENTLINE + " t4");
                where.append("\n left join t4." + ShipmentInOutLine.PROPERTY_SHIPMENTRECEIPT + " t5");
                where.append("\n where t2." + LCReceipt.PROPERTY_LANDEDCOST + " = :landedCost");
                where.append("\n order by t3." + LandedCostCost.PROPERTY_LINENO);
                where.append("\n , t5." + ShipmentInOut.PROPERTY_DOCUMENTNO);
                where.append("\n , t4." + ShipmentInOutLine.PROPERTY_LINENO);
                OBQuery<LCReceiptLineAmt> hql = OBDal.getInstance().createQuery(LCReceiptLineAmt.class,
                        where.toString());
                LandedCost landedCost = OBDal.getInstance().get(LandedCost.class, doc.getId());
                hql.setNamedParameter("landedCost", landedCost);
                line = hql.list().get(i / 2);
            } else if (doc.getEntityName().equals(LandedCostCost.ENTITY_NAME)) {
                if (((LandedCostCost) doc).getLandedCostMatchedList().size() == 1) {
                    line = ((LandedCostCost) doc).getLandedCostMatchedList().get(0);
                } else if (!((LandedCostCost) doc).getAmount().setScale(2, BigDecimal.ROUND_HALF_UP).equals(
                        ((LandedCostCost) doc).getMatchingAmount().setScale(2, BigDecimal.ROUND_HALF_UP))
                        && ((LandedCostCost) doc).isMatchingAdjusted()) {
                    if (i == 0) {
                        line = ((LandedCostCost) doc).getLandedCostMatchedList().get(0);
                    } else {
                        line = ((LandedCostCost) doc).getLandedCostMatchedList().get(1);
                    }
                } else {
                    line = ((LandedCostCost) doc).getLandedCostMatchedList().get(i / 2);
                }
            } else if (doc.getEntityName().equals(Invoice.ENTITY_NAME) && i > 0) {
                line = ((List<BaseOBObject>) OBDal.getInstance().get(doc.getClass(), doc.getId())
                        .get(lineListProperty)).get(i - 1);
            } else {
                line = ((List<BaseOBObject>) OBDal.getInstance().get(doc.getClass(), doc.getId())
                        .get(lineListProperty)).get(i / 2);
            }
            DocumentPostAssert documentPostAssert = documentPostAssertList.get(i);
            assertGeneralData(accountingFact);

            /* Accounting window fields assert */

            assertEquals(accountingFact.getTable(), table);
            assertEquals(accountingFact.getRecordID(), doc.getId());
            assertEquals(accountingFact.getAccountingSchema().getName(), "Main US/A/Euro");

            assertEquals(accountingFact.getAccount().getSearchKey(), documentPostAssert.getAccount());
            assertEquals(accountingFact.getQuantity(), documentPostAssert.getQuantity());

            BigDecimal rate;
            if ((productId != null && productId.equals(LANDEDCOSTTYPE3_ID))
                    || (doc.getEntityName().equals(Invoice.ENTITY_NAME)
                            && ((Invoice) doc).getCurrency().getId().equals(CURRENCY2_ID))
                    || (doc.getEntityName().equals(LandedCost.ENTITY_NAME)
                            && ((LCReceiptLineAmt) line).getLandedCostCost().getLandedCostType()
                                    .equals(OBDal.getInstance().get(Product.class, LANDEDCOSTTYPE3_ID)
                                            .getLandedCostTypeList().get(0)))
                    || (doc.getEntityName().equals(LandedCostCost.ENTITY_NAME)
                            && ((LCMatched) line).getInvoiceLine().getProduct() != null
                            && ((LCMatched) line).getInvoiceLine().getProduct().getId()
                                    .equals(LANDEDCOSTTYPE3_ID))
                    || (!doc.getEntityName().equals(LandedCostCost.ENTITY_NAME)
                            && !doc.getEntityName().equals(LandedCost.ENTITY_NAME)
                            && documentPostAssert.getProductId() != null
                            && !OBDal.getInstance().get(Product.class, documentPostAssert.getProductId())
                                    .getPricingProductPriceList().isEmpty()
                            && OBDal.getInstance().get(Product.class, documentPostAssert.getProductId())
                                    .getPricingProductPriceList().get(0).getPriceListVersion()
                                    .equals(OBDal.getInstance().get(Product.class, LANDEDCOSTTYPE3_ID)
                                            .getPricingProductPriceList().get(0).getPriceListVersion()))) {

                if (doc.getEntityName().equals(Invoice.ENTITY_NAME)
                        && ((Invoice) doc).getCurrencyConversionRateDocList().size() != 0) {
                    rate = ((Invoice) doc).getCurrencyConversionRateDocList().get(0).getRate();
                } else {
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(9999, 0, 1);
                    OBCriteria<ConversionRate> criteria = OBDal.getInstance()
                            .createCriteria(ConversionRate.class);
                    criteria.add(Restrictions.eq(ConversionRate.PROPERTY_CLIENT,
                            OBDal.getInstance().get(Client.class, CLIENT_ID)));
                    criteria.add(Restrictions.eq(ConversionRate.PROPERTY_CURRENCY,
                            OBDal.getInstance().get(Currency.class, CURRENCY2_ID)));
                    criteria.add(Restrictions.eq(ConversionRate.PROPERTY_TOCURRENCY,
                            OBDal.getInstance().get(Currency.class, CURRENCY1_ID)));
                    criteria.add(Restrictions.ge(ConversionRate.PROPERTY_VALIDTODATE, calendar.getTime()));
                    rate = criteria.list().get(0).getMultipleRateBy();
                }
            }

            else {
                rate = BigDecimal.ONE;
            }

            assertEquals(accountingFact.getDebit().setScale(2, BigDecimal.ROUND_HALF_UP),
                    documentPostAssert.getDebit().multiply(rate).setScale(2,
                            doc.getEntityName().equals(LandedCost.ENTITY_NAME) ? BigDecimal.ROUND_HALF_EVEN
                                    : BigDecimal.ROUND_HALF_UP));
            assertEquals(accountingFact.getCredit().setScale(2, BigDecimal.ROUND_HALF_UP),
                    documentPostAssert.getCredit().multiply(rate).setScale(2,
                            doc.getEntityName().equals(LandedCost.ENTITY_NAME) ? BigDecimal.ROUND_HALF_EVEN
                                    : BigDecimal.ROUND_HALF_UP));

            if ((productId != null && productId.equals(LANDEDCOSTTYPE3_ID))
                    || (doc.getEntityName().equals(Invoice.ENTITY_NAME)
                            && ((Invoice) doc).getCurrency().getId().equals(CURRENCY2_ID))
                    || (doc.getEntityName().equals(LandedCost.ENTITY_NAME)
                            && ((LCReceiptLineAmt) line).getLandedCostCost().getLandedCostType()
                                    .equals(OBDal.getInstance().get(Product.class, LANDEDCOSTTYPE3_ID)
                                            .getLandedCostTypeList().get(0)))
                    || (doc.getEntityName().equals(LandedCostCost.ENTITY_NAME)
                            && ((LCMatched) line).getInvoiceLine().getProduct() != null && ((LCMatched) line)
                                    .getInvoiceLine().getProduct().getId().equals(LANDEDCOSTTYPE3_ID))) {
                rate = BigDecimal.ONE;
            }

            else if ((doc.getEntityName().equals(ShipmentInOut.ENTITY_NAME)
                    || doc.getEntityName().equals(CostAdjustment.ENTITY_NAME))
                    && OBDal.getInstance().get(Organization.class, ORGANIZATION_ID).getCurrency() != null
                    && OBDal.getInstance().get(Organization.class, ORGANIZATION_ID).getCurrency().getId()
                            .equals(CURRENCY2_ID)) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(9999, 0, 1);
                OBCriteria<ConversionRate> criteria = OBDal.getInstance().createCriteria(ConversionRate.class);
                criteria.add(Restrictions.eq(ConversionRate.PROPERTY_CLIENT,
                        OBDal.getInstance().get(Client.class, CLIENT_ID)));
                criteria.add(Restrictions.eq(ConversionRate.PROPERTY_CURRENCY,
                        OBDal.getInstance().get(Currency.class, CURRENCY1_ID)));
                criteria.add(Restrictions.eq(ConversionRate.PROPERTY_TOCURRENCY,
                        OBDal.getInstance().get(Currency.class, CURRENCY2_ID)));
                criteria.add(Restrictions.ge(ConversionRate.PROPERTY_VALIDTODATE, calendar.getTime()));
                rate = criteria.list().get(0).getMultipleRateBy();
            }

            assertEquals(accountingFact.getForeignCurrencyDebit().setScale(2, BigDecimal.ROUND_HALF_UP),
                    documentPostAssert.getDebit().multiply(rate).setScale(2,
                            doc.getEntityName().equals(LandedCost.ENTITY_NAME) ? BigDecimal.ROUND_HALF_EVEN
                                    : BigDecimal.ROUND_HALF_UP));
            assertEquals(accountingFact.getForeignCurrencyCredit().setScale(2, BigDecimal.ROUND_HALF_UP),
                    documentPostAssert.getCredit().multiply(rate).setScale(2,
                            doc.getEntityName().equals(LandedCost.ENTITY_NAME) ? BigDecimal.ROUND_HALF_EVEN
                                    : BigDecimal.ROUND_HALF_UP));

            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(accountingFact.getAccountingDate());
            calendar1.set(Calendar.DAY_OF_MONTH, calendar1.getActualMinimum(Calendar.DAY_OF_MONTH));
            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(accountingFact.getAccountingDate());
            calendar2.set(Calendar.DAY_OF_MONTH, calendar2.getActualMaximum(Calendar.DAY_OF_MONTH));
            final OBCriteria<Period> criteria3 = OBDal.getInstance().createCriteria(Period.class);
            criteria3.add(Restrictions.eq(Period.PROPERTY_STARTINGDATE, calendar1.getTime()));
            criteria3.add(Restrictions.eq(Period.PROPERTY_ENDINGDATE, calendar2.getTime()));
            assertEquals(accountingFact.getPeriod(), criteria3.list().get(0));

            if (doc.getEntityName().equals(CostAdjustment.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()), formatDate(today));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((CostAdjustmentLine) line).getAccountingDate()));
                if (((CostAdjustmentLine) line).getInventoryTransaction().getGoodsShipmentLine() != null) {
                    assertEquals(accountingFact.getBusinessPartner(),
                            ((CostAdjustmentLine) line).getInventoryTransaction().getGoodsShipmentLine()
                                    .getShipmentReceipt().getBusinessPartner());
                } else {
                    assertEquals(accountingFact.getBusinessPartner(), null);
                }
            } else if (doc.getEntityName().equals(InventoryCount.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate(((InventoryCount) doc).getMovementDate()));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((InventoryCount) doc).getMovementDate()));
                assertEquals(accountingFact.getBusinessPartner(), null);
            } else if (doc.getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate(((ReceiptInvoiceMatch) doc).getTransactionDate()));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((ReceiptInvoiceMatch) doc).getTransactionDate()));
                assertEquals(accountingFact.getBusinessPartner(),
                        ((ReceiptInvoiceMatch) doc).getInvoiceLine().getBusinessPartner());
            } else if (doc.getEntityName().equals(InternalMovement.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate(((InternalMovement) doc).getMovementDate()));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((InternalMovement) doc).getMovementDate()));
                assertEquals(accountingFact.getBusinessPartner(), null);
            } else if (doc.getEntityName().equals(InternalConsumption.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate(((InternalConsumption) doc).getMovementDate()));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((InternalConsumption) doc).getMovementDate()));
                assertEquals(accountingFact.getBusinessPartner(), null);
            } else if (doc.getEntityName().equals(ProductionTransaction.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate(((ProductionTransaction) doc).getMovementDate()));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((ProductionTransaction) doc).getMovementDate()));
                assertEquals(accountingFact.getBusinessPartner(), null);
            } else if (doc.getEntityName().equals(LandedCost.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate(((LandedCost) doc).getReferenceDate()));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((LandedCost) doc).getReferenceDate()));
                if (i % 2 == 0) {
                    assertEquals(accountingFact.getBusinessPartner(),
                            OBDal.getInstance()
                                    .get(ShipmentInOutLine.class,
                                            ((LCReceiptLineAmt) line).getGoodsShipmentLine().getId())
                                    .getBusinessPartner());
                } else {
                    assertEquals(accountingFact.getBusinessPartner(), null);
                }
            } else if (doc.getEntityName().equals(LandedCostCost.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate(((LandedCostCost) doc).getAccountingDate()));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((LandedCostCost) doc).getAccountingDate()));
                if (i == 0 || (documentPostAssert.getProductId() != null
                        && OBDal.getInstance()
                                .get(InvoiceLine.class,
                                        ((LandedCostCost) doc).getLandedCostMatchedList().get(0)
                                                .getInvoiceLine().getId())
                                .getProduct() != null
                        && documentPostAssert.getProductId()
                                .equals(OBDal.getInstance()
                                        .get(InvoiceLine.class, ((LandedCostCost) doc)
                                                .getLandedCostMatchedList().get(0).getInvoiceLine().getId())
                                        .getProduct().getId()))) {
                    assertEquals(accountingFact.getBusinessPartner(),
                            OBDal.getInstance().get(InvoiceLine.class, ((LandedCostCost) doc)
                                    .getLandedCostMatchedList().get(0).getInvoiceLine().getId())
                                    .getBusinessPartner());
                } else {
                    assertEquals(accountingFact.getBusinessPartner(), null);
                }
            } else {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate((Date) doc.get("accountingDate")));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate((Date) doc.get("accountingDate")));
                assertEquals(accountingFact.getBusinessPartner(), doc.get("businessPartner"));
            }

            if ((productId != null && productId.equals(LANDEDCOSTTYPE3_ID))
                    || (doc.getEntityName().equals(Invoice.ENTITY_NAME)
                            && ((Invoice) doc).getCurrency().getId().equals(CURRENCY2_ID))
                    || (doc.getEntityName().equals(LandedCost.ENTITY_NAME)
                            && ((LCReceiptLineAmt) line).getLandedCostCost().getLandedCostType()
                                    .equals(OBDal.getInstance().get(Product.class, LANDEDCOSTTYPE3_ID)
                                            .getLandedCostTypeList().get(0)))
                    || (doc.getEntityName().equals(LandedCostCost.ENTITY_NAME)
                            && ((LCMatched) line).getInvoiceLine().getProduct() != null
                            && ((LCMatched) line).getInvoiceLine().getProduct().getId()
                                    .equals(LANDEDCOSTTYPE3_ID))
                    || (!doc.getEntityName().equals(Invoice.ENTITY_NAME)
                            && !doc.getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME)
                            && OBDal.getInstance().get(Organization.class, ORGANIZATION_ID)
                                    .getCurrency() != null
                            && OBDal.getInstance().get(Organization.class, ORGANIZATION_ID).getCurrency()
                                    .getId().equals(CURRENCY2_ID))) {
                assertEquals(accountingFact.getCurrency(),
                        OBDal.getInstance().get(Currency.class, CURRENCY2_ID));
            } else {
                assertEquals(accountingFact.getCurrency(),
                        OBDal.getInstance().get(Currency.class, CURRENCY1_ID));
            }

            if (productId != null && productId.equals(LANDEDCOSTTYPE2_ID)) {
                if (i == 0) {
                    assertEquals(accountingFact.getProduct(), null);
                    assertEquals(accountingFact.getUOM(), null);
                    assertEquals(accountingFact.getTax(), null);
                } else if (i == 1) {
                    assertEquals(accountingFact.getProduct(), null);
                    assertEquals(accountingFact.getUOM(), null);
                    assertEquals(accountingFact.getLineID(), null);
                    assertEquals(accountingFact.getRecordID2(), null);

                    OBCriteria<TaxRate> criteria = OBDal.getInstance().createCriteria(TaxRate.class);
                    criteria.add(Restrictions.eq(TaxRate.PROPERTY_TAXCATEGORY,
                            OBDal.getInstance().get(Product.class, productId).getTaxCategory()));
                    criteria.add(Restrictions.eq(TaxRate.PROPERTY_ORGANIZATION,
                            OBDal.getInstance().get(Organization.class, ORGANIZATION_ID)));
                    assertEquals(accountingFact.getTax(), criteria.list().get(0));
                } else {
                    assertEquals(accountingFact.getProduct().getId(), productId);
                    assertEquals(accountingFact.getUOM(), line.get("uOM"));
                    assertEquals(accountingFact.getLineID(), line.getId());
                    assertEquals(accountingFact.getRecordID2(), null);
                    assertEquals(accountingFact.getTax(), null);
                }
            }

            else {
                if (doc.getEntityName().equals(Invoice.ENTITY_NAME) && i == 0) {
                    assertEquals(accountingFact.getProduct(), null);
                    assertEquals(accountingFact.getUOM(), null);
                    assertEquals(accountingFact.getTax(), null);
                } else {
                    if (productId == null) {
                        assertEquals(accountingFact.getProduct(), documentPostAssert.getProductId() == null
                                ? null
                                : OBDal.getInstance().get(Product.class, documentPostAssert.getProductId()));
                    } else {
                        assertEquals(accountingFact.getProduct().getId(), productId);
                    }
                    if (line.getEntity().getProperty("uOM", false) == null) {
                        assertEquals(accountingFact.getUOM(), null);
                    } else {
                        assertEquals(accountingFact.getUOM(), line.get("uOM"));
                    }
                    if (!doc.getEntityName().equals(LandedCost.ENTITY_NAME)) {
                        assertEquals(accountingFact.getLineID(), line.getId());
                    }
                    assertEquals(accountingFact.getRecordID2(), null);
                    assertEquals(accountingFact.getTax(), null);
                }
            }

            assertEquals(accountingFact.getProject(), null);
            assertEquals(accountingFact.getCostcenter(), null);
            assertEquals(accountingFact.getAsset(), null);
            assertEquals(accountingFact.getStDimension(), null);
            assertEquals(accountingFact.getNdDimension(), null);

            /* Rest of fields assert */

            if (doc.getEntityName().equals(ShipmentInOut.ENTITY_NAME)) {
                assertEquals(accountingFact.getGLCategory().getName(), "Material Management");
            } else if (doc.getEntityName().equals(Invoice.ENTITY_NAME)) {
                assertEquals(accountingFact.getGLCategory().getName(), "AP Invoice");
            } else if (doc.getEntityName().equals(CostAdjustment.ENTITY_NAME)) {
                assertEquals(accountingFact.getGLCategory().getName(), "None");
            } else {
                assertEquals(accountingFact.getGLCategory().getName(), "Standard");
            }

            assertEquals(accountingFact.getPostingType(), "A");

            if (doc.getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME)) {
                assertEquals(accountingFact.getStorageBin(), null);
            } else if (doc.getEntityName().equals(InternalMovement.ENTITY_NAME)) {
                if (i % 2 == 0) {
                    assertEquals(accountingFact.getStorageBin(),
                            line.get(InternalMovementLine.PROPERTY_STORAGEBIN));
                } else {
                    assertEquals(accountingFact.getStorageBin(),
                            line.get(InternalMovementLine.PROPERTY_NEWSTORAGEBIN));
                }
            } else if (line.getEntity().getProperty("storageBin", false) == null) {
                assertEquals(accountingFact.getStorageBin(), null);
            } else {
                assertEquals(accountingFact.getStorageBin(), line.get("storageBin"));
            }

            if (doc.getEntityName().equals(InventoryCount.ENTITY_NAME)) {
                assertEquals(accountingFact.getDocumentType(), null);
                assertEquals(accountingFact.getDocumentCategory(), "MMI");
            } else if (doc.getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME)) {
                assertEquals(accountingFact.getDocumentType(), null);
                assertEquals(accountingFact.getDocumentCategory(), "MXI");
            } else if (doc.getEntityName().equals(InternalMovement.ENTITY_NAME)) {
                assertEquals(accountingFact.getDocumentType(), null);
                assertEquals(accountingFact.getDocumentCategory(), "MMM");
            } else if (doc.getEntityName().equals(InternalConsumption.ENTITY_NAME)) {
                assertEquals(accountingFact.getDocumentType(), null);
                assertEquals(accountingFact.getDocumentCategory(), "MIC");
            } else if (doc.getEntityName().equals(ProductionTransaction.ENTITY_NAME)) {
                assertEquals(accountingFact.getDocumentType(), null);
                assertEquals(accountingFact.getDocumentCategory(), "MMP");
            } else if (doc.getEntityName().equals(LandedCost.ENTITY_NAME)) {
                assertEquals(accountingFact.getDocumentType(), null);
                assertEquals(accountingFact.getDocumentCategory(), "LDC");
            } else if (doc.getEntityName().equals(LandedCostCost.ENTITY_NAME)) {
                assertEquals(accountingFact.getDocumentType(), null);
                assertEquals(accountingFact.getDocumentCategory(), "LCC");
            } else {
                assertEquals(accountingFact.getDocumentType(), doc.get("documentType"));
                assertEquals(accountingFact.getDocumentCategory(),
                        ((DocumentType) doc.get("documentType")).getDocumentCategory());
            }

            assertEquals(accountingFact.getSalesRegion(), null);
            assertEquals(accountingFact.getSalesCampaign(), null);
            assertEquals(accountingFact.getActivity(), null);
            assertEquals(accountingFact.getGroupID(), groupId);
            assertEquals(accountingFact.getType(), "N");
            assertEquals(accountingFact.getValue(), documentPostAssert.getAccount());
            assertEquals(accountingFact.getWithholding(), null);
            assertFalse(accountingFact.isModify());
            assertEquals(accountingFact.getDateBalanced(), null);

            final OBCriteria<ElementValue> criteria4 = OBDal.getInstance().createCriteria(ElementValue.class);
            criteria4.add(Restrictions.eq(ElementValue.PROPERTY_SEARCHKEY, documentPostAssert.getAccount()));
            assertEquals(accountingFact.getAccountingEntryDescription(),
                    criteria4.list().get(0).getDescription());

            i++;
        }
    } catch (Exception e) {
        throw new OBException(e);
    }
}

From source file:com.icesoft.faces.component.selectinputdate.SelectInputDateRenderer.java

public void encodeEnd(FacesContext facesContext, UIComponent uiComponent) throws IOException {
    validateParameters(facesContext, uiComponent, SelectInputDate.class);
    DOMContext domContext = DOMContext.attachDOMContext(facesContext, uiComponent);
    SelectInputDate selectInputDate = (SelectInputDate) uiComponent;

    Date value;/* w ww .j  a va  2 s.  co m*/
    boolean actuallyHaveTime = false;
    if (selectInputDate.isNavEvent()) {
        if (log.isTraceEnabled()) {
            log.trace("Rendering Nav Event");
        }
        value = selectInputDate.getNavDate();
        //System.out.println("navDate: " + value);
    } else if (selectInputDate.isRenderAsPopup() && !selectInputDate.isEnterKeyPressed(facesContext)) {
        value = selectInputDate.getPopupDate();
        if (value != null) {
            actuallyHaveTime = true;
        }
    } else {
        if (log.isTraceEnabled()) {
            log.trace("Logging non nav event");
        }
        value = CustomComponentUtils.getDateValue(selectInputDate);
        if (value != null) {
            actuallyHaveTime = true;
        }
        //System.out.println("CustomComponentUtils.getDateValue: " + value);
    }

    DateTimeConverter converter = selectInputDate.resolveDateTimeConverter(facesContext);
    TimeZone tz = selectInputDate.resolveTimeZone(facesContext);
    Locale currentLocale = selectInputDate.resolveLocale(facesContext);
    DateFormatSymbols symbols = new DateFormatSymbols(currentLocale);

    //System.out.println("SIDR.encodeEnd()  timezone: " + tz);
    //System.out.println("SIDR.encodeEnd()  locale: " + currentLocale);

    Calendar timeKeeper = Calendar.getInstance(tz, currentLocale);
    timeKeeper.setTime(value != null ? value : new Date());

    // get the parentForm
    UIComponent parentForm = findForm(selectInputDate);
    // if there is no parent form - ERROR
    if (parentForm == null) {
        log.error("SelectInputDate::must be in a FORM");
        return;
    }
    String clientId;
    if (!domContext.isInitialized()) {
        Element root = domContext.createRootElement(HTML.DIV_ELEM);
        boolean popupState = selectInputDate.isShowPopup();

        clientId = uiComponent.getClientId(facesContext);
        if (uiComponent.getId() != null)
            root.setAttribute("id", clientId + ROOT_DIV);

        Element table = domContext.createElement(HTML.TABLE_ELEM);
        if (selectInputDate.isRenderAsPopup()) {
            if (log.isTraceEnabled()) {
                log.trace("Render as popup");
            }
            // ICE-2492
            root.setAttribute(HTML.CLASS_ATTR,
                    Util.getQualifiedStyleClass(uiComponent, CSS_DEFAULT.DEFAULT_CALENDARPOPUP_CLASS, false));
            Element dateText = domContext.createElement(HTML.INPUT_ELEM);
            //System.out.println("value: " + selectInputDate.getValue());

            dateText.setAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_TEXT); // ICE-2302
            dateText.setAttribute(HTML.VALUE_ATTR, selectInputDate.getTextToRender());
            dateText.setAttribute(HTML.ID_ATTR, clientId + SelectInputDate.CALENDAR_INPUTTEXT);
            dateText.setAttribute(HTML.NAME_ATTR, clientId + SelectInputDate.CALENDAR_INPUTTEXT);
            dateText.setAttribute(HTML.CLASS_ATTR, selectInputDate.getCalendarInputClass());
            dateText.setAttribute(HTML.ONFOCUS_ATTR, "setFocus('');");
            dateText.setAttribute("onkeypress", this.ICESUBMIT);
            boolean withinSingleSubmit = org.icefaces.impl.util.Util.withinSingleSubmit(selectInputDate);
            if (withinSingleSubmit) {
                JavascriptContext.addJavascriptCall(facesContext,
                        "ice.cancelSingleSubmit('" + clientId + ROOT_DIV + "');");
            }
            String singleSubmitCall = "ice.fullSubmit('@this', '@all', event, this, function(p) { p('ice.submit.type', 'ice.se'); p('ice.submit.serialization', 'form');});";
            String onblur = combinedPassThru("setFocus('');",
                    selectInputDate.getPartialSubmit() ? ICESUBMITPARTIAL
                            : withinSingleSubmit ? singleSubmitCall : null);
            dateText.setAttribute(HTML.ONBLUR_ATTR, onblur);
            if (selectInputDate.getTabindex() != null) {
                dateText.setAttribute(HTML.TABINDEX_ATTR, selectInputDate.getTabindex());
            }
            if (selectInputDate.getAutocomplete() != null
                    && "off".equalsIgnoreCase(selectInputDate.getAutocomplete())) {
                dateText.setAttribute(HTML.AUTOCOMPLETE_ATTR, "off");
            }
            String tooltip = null;
            tooltip = selectInputDate.getInputTitle();
            if (tooltip == null || tooltip.length() == 0) {
                // extract the popupdate format and use it as a tooltip
                tooltip = getMessageWithParamFromResource(facesContext, INPUT_TEXT_TITLE,
                        selectInputDate.getSpecifiedPopupDateFormat());
            }
            if (tooltip != null && tooltip.length() > 0) {
                dateText.setAttribute(HTML.TITLE_ATTR, tooltip);
            }
            if (selectInputDate.isDisabled()) {
                dateText.setAttribute(HTML.DISABLED_ATTR, HTML.DISABLED_ATTR);
            }
            if (selectInputDate.isReadonly()) {
                dateText.setAttribute(HTML.READONLY_ATTR, HTML.READONLY_ATTR);
            }
            int maxlength = selectInputDate.getMaxlength();
            if (maxlength > 0) {
                dateText.setAttribute(HTML.MAXLENGTH_ATTR, String.valueOf(maxlength));
            }
            root.appendChild(dateText);
            Element calendarButton = domContext.createElement(HTML.INPUT_ELEM);
            calendarButton.setAttribute(HTML.ID_ATTR, clientId + CALENDAR_BUTTON);
            calendarButton.setAttribute(HTML.NAME_ATTR, clientId + CALENDAR_BUTTON);
            calendarButton.setAttribute(HTML.TYPE_ATTR, "image");
            calendarButton.setAttribute(HTML.ONFOCUS_ATTR, "setFocus('');");
            calendarButton.setAttribute(HTML.ONMOUSEDOWN_ATTR,
                    "if (Event.isLeftClick(event)) this.selfClick = true;");
            calendarButton.setAttribute(HTML.ONKEYDOWN_ATTR,
                    "if (event.keyCode == 13 || event.keyCode == 32) this.selfClick = true;");
            // render onclick to set value of hidden field to true
            String formClientId = parentForm.getClientId(facesContext);
            String hiddenValue1 = "document.forms['" + formClientId + "']['"
                    + this.getLinkId(facesContext, uiComponent) + "'].value='";
            String hiddenValue2 = "document.forms['" + formClientId + "']['"
                    + getHiddenFieldName(facesContext, uiComponent) + "'].value='";
            String onClick = "if (!this.selfClick) return false; this.selfClick = false; " + hiddenValue1
                    + clientId + CALENDAR_BUTTON + "';" + hiddenValue2 + "toggle';"
                    + "iceSubmitPartial( document.forms['" + formClientId + "'], this,event);" + hiddenValue1
                    + "';" + hiddenValue2 + "';" + "Ice.Calendar.addCloseListener('" + clientId + "','"
                    + formClientId + "','" + this.getLinkId(facesContext, uiComponent) + "','"
                    + getHiddenFieldName(facesContext, uiComponent) + "');" + "return false;";
            calendarButton.setAttribute(HTML.ONCLICK_ATTR, onClick);
            if (selectInputDate.getTabindex() != null) {
                try {
                    int tabIndex = Integer.valueOf(selectInputDate.getTabindex()).intValue();
                    tabIndex += 1;
                    calendarButton.setAttribute(HTML.TABINDEX_ATTR, String.valueOf(tabIndex));
                } catch (NumberFormatException e) {
                    if (log.isInfoEnabled()) {
                        log.info("NumberFormatException on tabindex");
                    }
                }
            }

            if (selectInputDate.isDisabled()) {
                calendarButton.setAttribute(HTML.DISABLED_ATTR, HTML.DISABLED_ATTR);
            }
            if (selectInputDate.isReadonly()) {
                calendarButton.setAttribute(HTML.READONLY_ATTR, HTML.READONLY_ATTR);
            }
            root.appendChild(calendarButton);
            // render a hidden field to manage the popup state; visible || hidden
            FormRenderer.addHiddenField(facesContext, getHiddenFieldName(facesContext, uiComponent));
            String resolvedSrc;
            if (popupState) {
                JavascriptContext.addJavascriptCall(facesContext, "Ice.util.adjustMyPosition('" + clientId
                        + CALENDAR_TABLE + "', '" + clientId + ROOT_DIV + "');");
                if (selectInputDate.isImageDirSet()) {
                    resolvedSrc = CoreUtils.resolveResourceURL(facesContext,
                            selectInputDate.getImageDir() + selectInputDate.getClosePopupImage());
                } else {
                    // ICE-2127: allow override of button images via CSS
                    calendarButton.setAttribute(HTML.CLASS_ATTR, selectInputDate.getClosePopupClass());
                    // without this Firefox would display a default text on top of the image
                    resolvedSrc = CoreUtils.resolveResourceURL(facesContext,
                            selectInputDate.getImageDir() + "spacer.gif");
                }
                calendarButton.setAttribute(HTML.SRC_ATTR, resolvedSrc);
                addAttributeToElementFromResource(facesContext, CLOSE_POPUP_ALT, calendarButton, HTML.ALT_ATTR);
                addAttributeToElementFromResource(facesContext, CLOSE_POPUP_TITLE, calendarButton,
                        HTML.TITLE_ATTR);
            } else {
                if (selectInputDate.isImageDirSet()) {
                    resolvedSrc = CoreUtils.resolveResourceURL(facesContext,
                            selectInputDate.getImageDir() + selectInputDate.getOpenPopupImage());
                } else {
                    // ICE-2127: allow override of button images via CSS
                    calendarButton.setAttribute(HTML.CLASS_ATTR, selectInputDate.getOpenPopupClass());
                    // without this Firefox would display a default text on top of the image
                    resolvedSrc = CoreUtils.resolveResourceURL(facesContext,
                            selectInputDate.getImageDir() + "spacer.gif");
                }
                calendarButton.setAttribute(HTML.SRC_ATTR, resolvedSrc);
                addAttributeToElementFromResource(facesContext, OPEN_POPUP_ALT, calendarButton, HTML.ALT_ATTR);
                addAttributeToElementFromResource(facesContext, OPEN_POPUP_TITLE, calendarButton,
                        HTML.TITLE_ATTR);
                FormRenderer.addHiddenField(facesContext, formClientId
                        + UINamingContainer.getSeparatorChar(FacesContext.getCurrentInstance()) + "j_idcl");
                FormRenderer.addHiddenField(facesContext, clientId + CALENDAR_CLICK);
                PassThruAttributeRenderer.renderHtmlAttributes(facesContext, uiComponent,
                        passThruAttributesWithoutTabindex);
                domContext.stepOver();
                return;
            }

            Text br = domContext.createTextNodeUnescaped("<br/>");
            root.appendChild(br);

            Element calendarDiv = domContext.createElement(HTML.DIV_ELEM);
            calendarDiv.setAttribute(HTML.ID_ATTR, clientId + CALENDAR_POPUP);
            calendarDiv.setAttribute(HTML.NAME_ATTR, clientId + CALENDAR_POPUP);
            calendarDiv.setAttribute(HTML.STYLE_ELEM, "position:absolute;z-index:10;");
            addAttributeToElementFromResource(facesContext, POPUP_CALENDAR_TITLE, calendarDiv, HTML.TITLE_ATTR);
            table.setAttribute(HTML.ID_ATTR, clientId + CALENDAR_TABLE);
            table.setAttribute(HTML.NAME_ATTR, clientId + CALENDAR_TABLE);
            table.setAttribute(HTML.CLASS_ATTR, selectInputDate.getStyleClass());
            table.setAttribute(HTML.STYLE_ATTR, "position:absolute;");
            table.setAttribute(HTML.CELLPADDING_ATTR, "0");
            table.setAttribute(HTML.CELLSPACING_ATTR, "0");
            // set mouse events on table bug 372
            String mouseOver = selectInputDate.getOnmouseover();
            table.setAttribute(HTML.ONMOUSEOVER_ATTR, mouseOver);
            String mouseOut = selectInputDate.getOnmouseout();
            table.setAttribute(HTML.ONMOUSEOUT_ATTR, mouseOut);
            String mouseMove = selectInputDate.getOnmousemove();
            table.setAttribute(HTML.ONMOUSEMOVE_ATTR, mouseMove);

            addAttributeToElementFromResource(facesContext, POPUP_CALENDAR_SUMMARY, table, HTML.SUMMARY_ATTR);
            Element positionDiv = domContext.createElement(HTML.DIV_ELEM);
            positionDiv.appendChild(table);
            calendarDiv.appendChild(positionDiv);
            Text iframe = domContext.createTextNodeUnescaped("<!--[if lte IE" + " 6.5]><iframe src='"
                    + CoreUtils.resolveResourceURL(FacesContext.getCurrentInstance(), "/xmlhttp/blank")
                    + "' class=\"iceSelInpDateIFrameFix\"></iframe><![endif]-->");
            calendarDiv.appendChild(iframe);
            root.appendChild(calendarDiv);

        } else {
            if (log.isTraceEnabled()) {
                log.trace("Select input Date Normal");
            }
            table.setAttribute(HTML.ID_ATTR, clientId + CALENDAR_TABLE);
            table.setAttribute(HTML.NAME_ATTR, clientId + CALENDAR_TABLE);
            table.setAttribute(HTML.CLASS_ATTR, selectInputDate.getStyleClass());
            addAttributeToElementFromResource(facesContext, CALENDAR_TITLE, table, HTML.TITLE_ATTR);
            table.setAttribute(HTML.CELLPADDING_ATTR, "0");
            table.setAttribute(HTML.CELLSPACING_ATTR, "0");
            // set mouse events on table bug 372
            String mouseOver = selectInputDate.getOnmouseover();
            table.setAttribute(HTML.ONMOUSEOVER_ATTR, mouseOver);
            String mouseOut = selectInputDate.getOnmouseout();
            table.setAttribute(HTML.ONMOUSEOUT_ATTR, mouseOut);
            String mouseMove = selectInputDate.getOnmousemove();
            table.setAttribute(HTML.ONMOUSEMOVE_ATTR, mouseMove);
            addAttributeToElementFromResource(facesContext, CALENDAR_SUMMARY, table, HTML.SUMMARY_ATTR);
            root.appendChild(table);

            Element dateText = domContext.createElement(HTML.INPUT_ELEM);
            dateText.setAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_HIDDEN);
            dateText.setAttribute(HTML.VALUE_ATTR, selectInputDate.getTextToRender());
            dateText.setAttribute(HTML.ID_ATTR, clientId + SelectInputDate.CALENDAR_INPUTTEXT);
            dateText.setAttribute(HTML.NAME_ATTR, clientId + SelectInputDate.CALENDAR_INPUTTEXT);
            root.appendChild(dateText);
        }
    }
    clientId = uiComponent.getClientId(facesContext);

    String[] weekdays = mapWeekdays(symbols);
    String[] weekdaysLong = mapWeekdaysLong(symbols);
    String[] months = mapMonths(symbols);

    // use the currentDay to set focus - do not set
    int lastDayInMonth = timeKeeper.getActualMaximum(Calendar.DAY_OF_MONTH);
    int currentDay = timeKeeper.get(Calendar.DAY_OF_MONTH); // starts at 1

    if (currentDay > lastDayInMonth) {
        currentDay = lastDayInMonth;
    }

    timeKeeper.set(Calendar.DAY_OF_MONTH, 1);

    int weekDayOfFirstDayOfMonth = mapCalendarDayToCommonDay(timeKeeper.get(Calendar.DAY_OF_WEEK));

    int weekStartsAtDayIndex = mapCalendarDayToCommonDay(timeKeeper.getFirstDayOfWeek());

    // do not require a writer - clean out all methods that reference a writer
    ResponseWriter writer = facesContext.getResponseWriter();

    Element root = (Element) domContext.getRootNode();

    Element table = null;
    if (selectInputDate.isRenderAsPopup()) {
        if (log.isTraceEnabled()) {
            log.trace("SelectInputDate as Popup");
        }

        // assumption input text is first child
        Element dateText = (Element) root.getFirstChild();
        //System.out.println("dateText  currentValue: " + currentValue);
        dateText.setAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_TEXT); // ICE-2302
        dateText.setAttribute(HTML.VALUE_ATTR, selectInputDate.getTextToRender());
        int maxlength = selectInputDate.getMaxlength();
        if (maxlength > 0) {
            dateText.setAttribute(HTML.MAXLENGTH_ATTR, String.valueOf(maxlength));
        }

        // get tables , our table is the first and only one
        NodeList tables = root.getElementsByTagName(HTML.TABLE_ELEM);
        // assumption we want the first table in tables. there should only be one
        table = (Element) tables.item(0);

        PassThruAttributeRenderer.renderHtmlAttributes(facesContext, uiComponent,
                passThruAttributesWithoutTabindex);

        Element tr1 = domContext.createElement(HTML.TR_ELEM);

        table.appendChild(tr1);
        writeMonthYearHeader(domContext, facesContext, writer, selectInputDate, timeKeeper, currentDay, tr1,
                selectInputDate.getMonthYearRowClass(), currentLocale, months, weekdays, weekdaysLong,
                converter);

        Element tr2 = domContext.createElement(HTML.TR_ELEM);
        table.appendChild(tr2);

        writeWeekDayNameHeader(domContext, weekStartsAtDayIndex, weekdays, facesContext, writer,
                selectInputDate, tr2, selectInputDate.getWeekRowClass(), timeKeeper, months, weekdaysLong,
                converter);

        writeDays(domContext, facesContext, writer, selectInputDate, timeKeeper, currentDay,
                weekStartsAtDayIndex, weekDayOfFirstDayOfMonth, lastDayInMonth, table, months, weekdays,
                weekdaysLong, converter, (actuallyHaveTime ? value : null));
    } else {
        if (log.isTraceEnabled()) {
            log.trace("renderNormal::endcodeEnd");
        }
        // assume table is the first child
        table = (Element) root.getFirstChild();

        PassThruAttributeRenderer.renderHtmlAttributes(facesContext, uiComponent, passThruAttributes);

        Element tr1 = domContext.createElement(HTML.TR_ELEM);
        table.appendChild(tr1);

        writeMonthYearHeader(domContext, facesContext, writer, selectInputDate, timeKeeper, currentDay, tr1,
                selectInputDate.getMonthYearRowClass(), currentLocale, months, weekdays, weekdaysLong,
                converter);

        Element tr2 = domContext.createElement(HTML.TR_ELEM);

        writeWeekDayNameHeader(domContext, weekStartsAtDayIndex, weekdays, facesContext, writer,
                selectInputDate, tr2, selectInputDate.getWeekRowClass(), timeKeeper, months, weekdaysLong,
                converter);

        table.appendChild(tr2);

        writeDays(domContext, facesContext, writer, selectInputDate, timeKeeper, currentDay,
                weekStartsAtDayIndex, weekDayOfFirstDayOfMonth, lastDayInMonth, table, months, weekdays,
                weekdaysLong, converter, (actuallyHaveTime ? value : null));
    }

    //System.out.println("SIDR.encodeEnd()  isTime? " + SelectInputDate.isTime(converter));
    if (SelectInputDate.isTime(converter)) {
        Element tfoot = domContext.createElement(HTML.TFOOT_ELEM);
        Element tr = domContext.createElement(HTML.TR_ELEM);
        Element td = domContext.createElement(HTML.TD_ELEM);
        td.setAttribute(HTML.COLSPAN_ATTR, selectInputDate.isRenderWeekNumbers() ? "8" : "7");
        td.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeClass());
        Element tbl = domContext.createElement(HTML.TABLE_ELEM);
        Element tr2 = domContext.createElement(HTML.TR_ELEM);
        Element tdHours = domContext.createElement(HTML.TD_ELEM);
        Element hours = domContext.createElement(HTML.SELECT_ELEM);
        hours.setAttribute(HTML.ID_ATTR, clientId + SELECT_HOUR);
        hours.setAttribute(HTML.NAME_ATTR, clientId + SELECT_HOUR);
        hours.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeDropDownClass());
        hours.setAttribute(HTML.ONCHANGE_ATTR, DomBasicRenderer.ICESUBMITPARTIAL);

        // Convert from an hour to an index into the list of hours
        int hrs[] = selectInputDate.getHours(facesContext);
        //System.out.println("SIDR.encodeEnd()  hrs: " + hrs[0] + ", " + hrs[hrs.length-1]);
        int hourIndex;
        int min;
        int sec;
        int amPm;
        //System.out.println("SIDR.encodeEnd()  actuallyHaveTime: " + actuallyHaveTime);
        if (!actuallyHaveTime && selectInputDate.getHoursSubmittedValue() != null
                && selectInputDate.getMinutesSubmittedValue() != null) {
            //System.out.println("SIDR.encodeEnd()  Using submitted hours and minutes");
            hourIndex = selectInputDate.getHoursSubmittedValue().intValue();
            //System.out.println("SIDR.encodeEnd()  hour: " + hourIndex);
            min = selectInputDate.getMinutesSubmittedValue().intValue();
            //System.out.println("SIDR.encodeEnd()  min: " + min);
            String amPmStr = selectInputDate.getAmPmSubmittedValue();
            //System.out.println("SIDR.encodeEnd()  amPmStr: " + amPmStr);
            if (amPmStr != null) {
                amPm = amPmStr.equalsIgnoreCase("PM") ? 1 : 0;
            } else {
                amPm = (hourIndex >= 12) ? 1 : 0;
            }
            //System.out.println("SIDR.encodeEnd()  amPm: " + amPm);
            if (hrs[0] == 1) {
                hourIndex--;
                if (hourIndex < 0) {
                    hourIndex = hrs.length - 1;
                }
            }
            //System.out.println("SIDR.encodeEnd()  hourIndex: " + hourIndex);
        } else {
            if (hrs.length > 12) {
                hourIndex = timeKeeper.get(Calendar.HOUR_OF_DAY);
                //System.out.println("SIDR.encodeEnd()  hour 24: " + hourIndex);
            } else {
                hourIndex = timeKeeper.get(Calendar.HOUR);
                //System.out.println("SIDR.encodeEnd()  hour 12: " + hourIndex);
            }
            if (hrs[0] == 1) {
                hourIndex--;
                if (hourIndex < 0) {
                    hourIndex = hrs.length - 1;
                }
            }
            //System.out.println("SIDR.encodeEnd()  hourIndex: " + hourIndex);

            min = timeKeeper.get(Calendar.MINUTE);
            amPm = timeKeeper.get(Calendar.AM_PM);
            //System.out.println("SIDR.encodeEnd()  amPm: " + amPm);
        }
        if (!actuallyHaveTime && selectInputDate.getSecondsSubmittedValue() != null) {
            sec = selectInputDate.getSecondsSubmittedValue().intValue();
        } else {
            sec = timeKeeper.get(Calendar.SECOND);
        }
        for (int i = 0; i < hrs.length; i++) {
            Element hoursOption = domContext.createElement(HTML.OPTION_ELEM);
            hoursOption.setAttribute(HTML.VALUE_ATTR, String.valueOf(hrs[i]));
            Text hourText = domContext.createTextNode(String.valueOf(hrs[i]));
            hoursOption.appendChild(hourText);
            if (i == hourIndex) {
                hoursOption.setAttribute(HTML.SELECTED_ATTR, "true");
            }
            hours.appendChild(hoursOption);
        }
        Element tdColon = domContext.createElement(HTML.TD_ELEM);
        Element tdMinutes = domContext.createElement(HTML.TD_ELEM);
        Element minutes = domContext.createElement(HTML.SELECT_ELEM);
        minutes.setAttribute(HTML.ID_ATTR, clientId + SELECT_MIN);
        minutes.setAttribute(HTML.NAME_ATTR, clientId + SELECT_MIN);
        minutes.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeDropDownClass());
        minutes.setAttribute(HTML.ONCHANGE_ATTR, DomBasicRenderer.ICESUBMITPARTIAL);
        for (int i = 0; i < 60; i++) {
            Element minutesOption = domContext.createElement(HTML.OPTION_ELEM);
            minutesOption.setAttribute(HTML.VALUE_ATTR, String.valueOf(i));
            String digits = String.valueOf(i);
            if (i < 10) {
                digits = "0" + digits;
            }
            Text minuteText = domContext.createTextNode(digits);
            minutesOption.appendChild(minuteText);
            if (i == min) {
                minutesOption.setAttribute(HTML.SELECTED_ATTR, "true");
            }
            minutes.appendChild(minutesOption);
        }

        Text colon = domContext.createTextNode(":");
        tfoot.appendChild(tr);
        tr.appendChild(td);
        td.appendChild(tbl);
        tbl.appendChild(tr2);
        tdHours.appendChild(hours);
        tr2.appendChild(tdHours);
        tdColon.appendChild(colon);
        tdMinutes.appendChild(minutes);
        tr2.appendChild(tdColon);
        tr2.appendChild(tdMinutes);

        if (selectInputDate.isSecond(facesContext)) {
            Element tdSeconds = domContext.createElement(HTML.TD_ELEM);
            Element tdSecColon = domContext.createElement(HTML.TD_ELEM);
            Element seconds = domContext.createElement(HTML.SELECT_ELEM);
            seconds.setAttribute(HTML.ID_ATTR, clientId + SELECT_SEC);
            seconds.setAttribute(HTML.NAME_ATTR, clientId + SELECT_SEC);
            seconds.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeDropDownClass());
            seconds.setAttribute(HTML.ONCHANGE_ATTR, DomBasicRenderer.ICESUBMITPARTIAL);
            for (int i = 0; i < 60; i++) {
                Element secondsOption = domContext.createElement(HTML.OPTION_ELEM);
                secondsOption.setAttribute(HTML.VALUE_ATTR, String.valueOf(i));
                String digits = String.valueOf(i);
                if (i < 10) {
                    digits = "0" + digits;
                }
                Text secondText = domContext.createTextNode(digits);
                secondsOption.appendChild(secondText);
                if (i == sec) {
                    secondsOption.setAttribute(HTML.SELECTED_ATTR, "true");
                }
                seconds.appendChild(secondsOption);
            }
            Text secondColon = domContext.createTextNode(":");
            tdSecColon.appendChild(secondColon);
            tdSeconds.appendChild(seconds);
            tr2.appendChild(tdSecColon);
            tr2.appendChild(tdSeconds);
        }

        if (selectInputDate.isAmPm(facesContext)) {
            Element tdAamPm = domContext.createElement(HTML.TD_ELEM);
            Element amPmElement = domContext.createElement(HTML.SELECT_ELEM);
            amPmElement.setAttribute(HTML.ID_ATTR, clientId + SELECT_AM_PM);
            amPmElement.setAttribute(HTML.NAME_ATTR, clientId + SELECT_AM_PM);
            amPmElement.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeDropDownClass());
            amPmElement.setAttribute(HTML.ONCHANGE_ATTR, DomBasicRenderer.ICESUBMITPARTIAL);
            String[] symbolsAmPm = symbols.getAmPmStrings();

            Element amPmElementOption = domContext.createElement(HTML.OPTION_ELEM);
            amPmElementOption.setAttribute(HTML.VALUE_ATTR, "AM");
            Text amPmElementText = domContext.createTextNode(symbolsAmPm[0]);
            amPmElementOption.appendChild(amPmElementText);

            Element amPmElementOption2 = domContext.createElement(HTML.OPTION_ELEM);
            amPmElementOption2.setAttribute(HTML.VALUE_ATTR, "PM");
            Text amPmElementText2 = domContext.createTextNode(symbolsAmPm[1]);
            amPmElementOption2.appendChild(amPmElementText2);
            if (amPm == 0) {
                amPmElementOption.setAttribute(HTML.SELECTED_ATTR, "true");
            } else {
                amPmElementOption2.setAttribute(HTML.SELECTED_ATTR, "true");
            }
            amPmElement.appendChild(amPmElementOption);
            amPmElement.appendChild(amPmElementOption2);
            tdAamPm.appendChild(amPmElement);
            tr2.appendChild(tdAamPm);
        }
        table.appendChild(tfoot);
    }
    // purge child components as they have been encoded no need to keep them around
    selectInputDate.getChildren().clear();

    // steps to the position where the next sibling should be rendered
    domContext.stepOver();
}

From source file:com.clark.func.Functions.java

/**
 * <p>//from www  .  j  a v a  2 s.  c o  m
 * Formats the time gap as a string, using the specified format. Padding the
 * left hand side of numbers with zeroes is optional and the timezone may be
 * specified.
 * </p>
 * 
 * <p>
 * When calculating the difference between months/days, it chooses to
 * calculate months first. So when working out the number of months and days
 * between January 15th and March 10th, it choose 1 month and 23 days gained
 * by choosing January->February = 1 month and then calculating days
 * forwards, and not the 1 month and 26 days gained by choosing March ->
 * February = 1 month and then calculating days backwards.
 * </p>
 * 
 * <p>
 * For more control, the <a href="http://joda-time.sf.net/">Joda-Time</a>
 * library is recommended.
 * </p>
 * 
 * @param startMillis
 *            the start of the duration
 * @param endMillis
 *            the end of the duration
 * @param format
 *            the way in which to format the duration
 * @param padWithZeros
 *            whether to pad the left hand side of numbers with 0's
 * @param timezone
 *            the millis are defined in
 * @return the time as a String
 */
public static String formatPeriod(long startMillis, long endMillis, String format, boolean padWithZeros,
        TimeZone timezone) {

    // Used to optimise for differences under 28 days and
    // called formatDuration(millis, format); however this did not work
    // over leap years.
    // TODO: Compare performance to see if anything was lost by
    // losing this optimisation.

    DurationToken[] tokens = lexx(format);

    // timezones get funky around 0, so normalizing everything to GMT
    // stops the hours being off
    Calendar start = Calendar.getInstance(timezone);
    start.setTime(new Date(startMillis));
    Calendar end = Calendar.getInstance(timezone);
    end.setTime(new Date(endMillis));

    // initial estimates
    int milliseconds = end.get(Calendar.MILLISECOND) - start.get(Calendar.MILLISECOND);
    int seconds = end.get(Calendar.SECOND) - start.get(Calendar.SECOND);
    int minutes = end.get(Calendar.MINUTE) - start.get(Calendar.MINUTE);
    int hours = end.get(Calendar.HOUR_OF_DAY) - start.get(Calendar.HOUR_OF_DAY);
    int days = end.get(Calendar.DAY_OF_MONTH) - start.get(Calendar.DAY_OF_MONTH);
    int months = end.get(Calendar.MONTH) - start.get(Calendar.MONTH);
    int years = end.get(Calendar.YEAR) - start.get(Calendar.YEAR);

    // each initial estimate is adjusted in case it is under 0
    while (milliseconds < 0) {
        milliseconds += 1000;
        seconds -= 1;
    }
    while (seconds < 0) {
        seconds += 60;
        minutes -= 1;
    }
    while (minutes < 0) {
        minutes += 60;
        hours -= 1;
    }
    while (hours < 0) {
        hours += 24;
        days -= 1;
    }

    if (DurationToken.containsTokenWithValue(tokens, DATE_M)) {
        while (days < 0) {
            days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
            months -= 1;
            start.add(Calendar.MONTH, 1);
        }

        while (months < 0) {
            months += 12;
            years -= 1;
        }

        if (!DurationToken.containsTokenWithValue(tokens, DATE_y) && years != 0) {
            while (years != 0) {
                months += 12 * years;
                years = 0;
            }
        }
    } else {
        // there are no M's in the format string

        if (!DurationToken.containsTokenWithValue(tokens, DATE_y)) {
            int target = end.get(Calendar.YEAR);
            if (months < 0) {
                // target is end-year -1
                target -= 1;
            }

            while ((start.get(Calendar.YEAR) != target)) {
                days += start.getActualMaximum(Calendar.DAY_OF_YEAR) - start.get(Calendar.DAY_OF_YEAR);

                // Not sure I grok why this is needed, but the brutal tests
                // show it is
                if (start instanceof GregorianCalendar) {
                    if ((start.get(Calendar.MONTH) == Calendar.FEBRUARY)
                            && (start.get(Calendar.DAY_OF_MONTH) == 29)) {
                        days += 1;
                    }
                }

                start.add(Calendar.YEAR, 1);

                days += start.get(Calendar.DAY_OF_YEAR);
            }

            years = 0;
        }

        while (start.get(Calendar.MONTH) != end.get(Calendar.MONTH)) {
            days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
            start.add(Calendar.MONTH, 1);
        }

        months = 0;

        while (days < 0) {
            days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
            months -= 1;
            start.add(Calendar.MONTH, 1);
        }

    }

    // The rest of this code adds in values that
    // aren't requested. This allows the user to ask for the
    // number of months and get the real count and not just 0->11.

    if (!DurationToken.containsTokenWithValue(tokens, DATE_d)) {
        hours += 24 * days;
        days = 0;
    }
    if (!DurationToken.containsTokenWithValue(tokens, DATE_H)) {
        minutes += 60 * hours;
        hours = 0;
    }
    if (!DurationToken.containsTokenWithValue(tokens, DATE_m)) {
        seconds += 60 * minutes;
        minutes = 0;
    }
    if (!DurationToken.containsTokenWithValue(tokens, DATE_s)) {
        milliseconds += 1000 * seconds;
        seconds = 0;
    }

    return formatPeriodTime(tokens, years, months, days, hours, minutes, seconds, milliseconds, padWithZeros);
}

From source file:com.clark.func.Functions.java

/**
 * <p>//  ww w. j a  v a2 s  .  c  o m
 * Internal calculation method.
 * </p>
 * 
 * @param val
 *            the calendar
 * @param field
 *            the field constant
 * @param modType
 *            type to truncate, round or ceiling
 * @throws ArithmeticException
 *             if the year is over 280 million
 */
private static void modifyDate(Calendar val, int field, int modType) {
    if (val.get(Calendar.YEAR) > 280000000) {
        throw new ArithmeticException("Calendar value too large for accurate calculations");
    }

    if (field == Calendar.MILLISECOND) {
        return;
    }

    // ----------------- Fix for LANG-59 ---------------------- START
    // ---------------
    // see http://issues.apache.org/jira/browse/LANG-59
    //
    // Manually truncate milliseconds, seconds and minutes, rather than
    // using
    // Calendar methods.

    Date date = val.getTime();
    long time = date.getTime();
    boolean done = false;

    // truncate milliseconds
    int millisecs = val.get(Calendar.MILLISECOND);
    if (MODIFY_TRUNCATE == modType || millisecs < 500) {
        time = time - millisecs;
    }
    if (field == Calendar.SECOND) {
        done = true;
    }

    // truncate seconds
    int seconds = val.get(Calendar.SECOND);
    if (!done && (MODIFY_TRUNCATE == modType || seconds < 30)) {
        time = time - (seconds * 1000L);
    }
    if (field == Calendar.MINUTE) {
        done = true;
    }

    // truncate minutes
    int minutes = val.get(Calendar.MINUTE);
    if (!done && (MODIFY_TRUNCATE == modType || minutes < 30)) {
        time = time - (minutes * 60000L);
    }

    // reset time
    if (date.getTime() != time) {
        date.setTime(time);
        val.setTime(date);
    }
    // ----------------- Fix for LANG-59 ----------------------- END
    // ----------------

    boolean roundUp = false;
    for (int i = 0; i < fields.length; i++) {
        for (int j = 0; j < fields[i].length; j++) {
            if (fields[i][j] == field) {
                // This is our field... we stop looping
                if (modType == MODIFY_CEILING || (modType == MODIFY_ROUND && roundUp)) {
                    if (field == SEMI_MONTH) {
                        // This is a special case that's hard to generalize
                        // If the date is 1, we round up to 16, otherwise
                        // we subtract 15 days and add 1 month
                        if (val.get(Calendar.DATE) == 1) {
                            val.add(Calendar.DATE, 15);
                        } else {
                            val.add(Calendar.DATE, -15);
                            val.add(Calendar.MONTH, 1);
                        }
                        // ----------------- Fix for LANG-440
                        // ---------------------- START ---------------
                    } else if (field == Calendar.AM_PM) {
                        // This is a special case
                        // If the time is 0, we round up to 12, otherwise
                        // we subtract 12 hours and add 1 day
                        if (val.get(Calendar.HOUR_OF_DAY) == 0) {
                            val.add(Calendar.HOUR_OF_DAY, 12);
                        } else {
                            val.add(Calendar.HOUR_OF_DAY, -12);
                            val.add(Calendar.DATE, 1);
                        }
                        // ----------------- Fix for LANG-440
                        // ---------------------- END ---------------
                    } else {
                        // We need at add one to this field since the
                        // last number causes us to round up
                        val.add(fields[i][0], 1);
                    }
                }
                return;
            }
        }
        // We have various fields that are not easy roundings
        int offset = 0;
        boolean offsetSet = false;
        // These are special types of fields that require different rounding
        // rules
        switch (field) {
        case SEMI_MONTH:
            if (fields[i][0] == Calendar.DATE) {
                // If we're going to drop the DATE field's value,
                // we want to do this our own way.
                // We need to subtrace 1 since the date has a minimum of
                // 1
                offset = val.get(Calendar.DATE) - 1;
                // If we're above 15 days adjustment, that means we're
                // in
                // the
                // bottom half of the month and should stay accordingly.
                if (offset >= 15) {
                    offset -= 15;
                }
                // Record whether we're in the top or bottom half of
                // that
                // range
                roundUp = offset > 7;
                offsetSet = true;
            }
            break;
        case Calendar.AM_PM:
            if (fields[i][0] == Calendar.HOUR_OF_DAY) {
                // If we're going to drop the HOUR field's value,
                // we want to do this our own way.
                offset = val.get(Calendar.HOUR_OF_DAY);
                if (offset >= 12) {
                    offset -= 12;
                }
                roundUp = offset >= 6;
                offsetSet = true;
            }
            break;
        }
        if (!offsetSet) {
            int min = val.getActualMinimum(fields[i][0]);
            int max = val.getActualMaximum(fields[i][0]);
            // Calculate the offset from the minimum allowed value
            offset = val.get(fields[i][0]) - min;
            // Set roundUp if this is more than half way between the minimum
            // and maximum
            roundUp = offset > ((max - min) / 2);
        }
        // We need to remove this field
        if (offset != 0) {
            val.set(fields[i][0], val.get(fields[i][0]) - offset);
        }
    }
    throw new IllegalArgumentException("The field " + field + " is not supported");

}