com.consult.app.dao.impl.UserDaoImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.consult.app.dao.impl.UserDaoImpl.java

Source

package com.consult.app.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.consult.app.cache.JUserCache;
import com.consult.app.cache.UserCache;
import com.consult.app.dao.UserDao;
import com.consult.app.dao.interceptor.CargoMessageInterceptor;
import com.consult.app.dao.interceptor.TruckMessageInterceptor;
import com.consult.app.dao.interceptor.strategy.MessageInterceptor;
import com.consult.app.modal.Position;
import com.consult.app.modal.Profile;
import com.consult.app.modal.UnregisterUser;
import com.consult.app.modal.User;
import com.consult.app.modal.Verify;
import com.consult.app.push.PushUtil;
import com.consult.app.request.CountRequest;
import com.consult.app.request.CountTypeRequest;
import com.consult.app.request.IdTypeBeforeAfterRequest;
import com.consult.app.request.TypeBeforeAfterRequest;
import com.consult.app.request.TypeRequest;
import com.consult.app.request.user.PostPositionRequest;
import com.consult.app.request.user.RegisterRequest;
import com.consult.app.request.user.SearchDriverRequest;
import com.consult.app.response.PasswordResponse;
import com.consult.app.response.ResultObjectResponse;
import com.consult.app.response.user.CargoMessageAuthItem;
import com.consult.app.response.user.MessageAuthenticateItem;
import com.consult.app.response.user.RegisterResponse;
import com.consult.app.utils.ConfigUtil;
import com.consult.app.utils.Constant;
import com.consult.app.utils.Cookie;
import com.consult.app.utils.MessageDigestGenerator;
import com.consult.app.utils.PositionHelper;
import com.consult.app.utils.RandomNumber;
import com.consult.app.utils.TimeUtils;

//13057583700@wo.com.cn
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory factory) {
        this.sessionFactory = factory;
    }

    public Long save(User user) {
        //      getHibernateTemplate().save(user);
        sessionFactory.getCurrentSession().save(user);
        return user.getUserId();
    }

    public void update(User user) {
        sessionFactory.getCurrentSession().update(user);
        JUserCache.getInstance().putUser(user.getUserId(), user);
    }

    public void delete(User user) {
        sessionFactory.getCurrentSession().delete(user);
    }

    public User findById(Long userId) {
        try {
            User user = JUserCache.getInstance().findUserByUserId(userId);
            if (user == null) {
                Query query = sessionFactory.getCurrentSession().createQuery("from User user where user.userId=?");
                query.setLong(0, userId);
                user = (User) query.uniqueResult();
                if (user != null) {
                    JUserCache.getInstance().saveUser(userId, user);
                }
            }
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public User findByIdNewSession(Long userId) {
        try {
            User user = JUserCache.getInstance().findUserByUserId(userId);
            if (user == null) {
                Session session = null;
                try {
                    session = sessionFactory.openSession();
                    Query query = session.createQuery("from User user where user.userId=?");
                    query.setLong(0, userId);
                    user = (User) query.uniqueResult();
                    if (user != null) {
                        JUserCache.getInstance().saveUser(userId, user);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                } finally {
                    if (session != null) {
                        session.close();
                        session = null;
                    }
                }
            }
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public RegisterResponse register(Long userId, RegisterRequest req, int smsLocate, long smsLocateInterval,
            UnregisterUser unUser) {
        RegisterResponse rp = new RegisterResponse(Cookie.RESPONSE_SUCCESS);
        long now = System.currentTimeMillis();
        User user = new User(userId, req.getVersion(), req.getPassword(), req.getFrom(),
                Long.valueOf(req.getTelephone()), now, now, req.getToken(), now,
                Math.abs(RandomNumber.createRandomLong()), Constant.USER_UNAUTHENTICATE);
        sessionFactory.getCurrentSession().save(user);
        Position position = new Position(user.getUserId(), now, smsLocate, now + smsLocateInterval);
        if (unUser != null) {
            position.setCreateTime(unUser.getCreateTime());
            position.setPositionTime(unUser.getPositionTime());
            position.setSmsLocate(unUser.getSmsLocate());
        }
        sessionFactory.getCurrentSession().save(position);
        Profile profile = new Profile();
        profile.setUserName(user.getTelephone().toString());
        profile.setUserId(user.getUserId());
        profile.setUserType(req.getUserType());
        profile.setUpdateTime(now);
        profile.setCreateTime(now);

        sessionFactory.getCurrentSession().save(profile);
        rp.setIsAuthenticate(Constant.USER_UNAUTHENTICATE);
        rp.setSessionId(user.getSessionId().toString());
        rp.setResult(Cookie.RESPONSE_SUCCESS);
        rp.setId(user.getUserId());
        rp.setPushSubscribe(user.getPushSubscribe());
        rp.setStrId(String.valueOf(user.getUserId()));
        rp.setHeartBeat(ConfigUtil.getInstance().getHeartbeatInterval());
        return rp;
    }

    @Override
    public ResultObjectResponse verifyTelephone(Long telephone, Verify verify) {
        ResultObjectResponse rp = new ResultObjectResponse(Cookie.RESPONSE_SUCCESS);
        try {

            if (isTelephoneExist(telephone) > 0) {
                // Already Exists!!
                rp.setResult(Cookie.RESPONSE_ALREADY_EXIST);
                return rp;
            }
            long now = System.currentTimeMillis();
            long endTime = now + Constant.VERIFY_TIMEOUT;
            String code = RandomNumber.generateVerifyCode();
            if (verify == null) {
                verify = new Verify(telephone, code, endTime, now, Constant.TYPE_NORMAL);
            } else {
                verify.setEndTime(endTime);
                verify.setUpdateTime(now);
                verify.setCode(code);
            }
            sessionFactory.getCurrentSession().saveOrUpdate(verify);
            rp.setResult(Cookie.RESPONSE_SUCCESS);
            rp.setInfo(code);
        } catch (Exception e) {
            e.printStackTrace();
            rp.setResult(Cookie.RESPONSE_SERVER_QUERY_ERROR);
        }
        return rp;
    }

    @Override
    public User findByTelephone(Long telephone) {
        try {
            Query query = sessionFactory.getCurrentSession().createQuery("from User user where user.telephone=?");
            query.setLong(0, telephone);
            return (User) query.uniqueResult();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int changePassword(long userId, String newPassword) {
        try {
            String hql = "update User user set user.password=? where user.userId=?";
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setString(0, newPassword);
            query.setLong(1, userId);
            query.executeUpdate();
            JUserCache.getInstance().removeUser(userId);
            return Cookie.RESPONSE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return Cookie.RESPONSE_SERVER_QUERY_ERROR;
        }

    }

    @Override
    public List<Object> getMessages(TypeBeforeAfterRequest req, int mode, long userId) {

        String condition = "", hql = "";
        MessageInterceptor inter = null;
        condition = " and message.updateTime>? and message.updateTime<=? order by message.updateTime desc";
        if (req.getType() == Constant.MESSAGE_TYPE_CARGO) {
            hql = "select new com.consult.app.response.cargo.MyCargoMessageItem"
                    + "(message.messageId, case when message.type>=1 and message.type<4 then 1 else 0 end, message.weight, message.capacity,"
                    + "message.truckType, message.contact, message.telephone, message.start, message.end,"
                    + "message.description, message.updateTime, message.truckLength, message.companyName, message.companyAddress, message.landlines,"
                    + "message.picture, message.avatarAuthenticate, message.userId, message.licenseAuthenticate, message.charges, message.cargoType, message.score, message.orderCount, message.messageCount, message.truckLengthSet) "
                    + "from CargoMessage message where message.userId=? and message.type>=1 and message.type<=4 ";
            inter = new CargoMessageInterceptor();
        } else if (req.getType() == Constant.MESSAGE_TYPE_FIXED) {
            // Noneed
            return null;
        } else if (req.getType() == Constant.MESSAGE_TYPE_TRUCK) {
            hql = "select new com.consult.app.response.truck.TruckMessageItem"
                    + "(message.messageId, message.userId, message.start, message.end, message.travelType,"
                    + "profile.userName, message.telephone, message.transfer, "
                    + "message.number, message.truckLength, message.truckLoad, message.truckType,"
                    + "case when message.type>=" + Constant.TYPE_NORMAL
                    + " then 1 else 0 end, message.description, "
                    + "message.updateTime, profile.picture, message.commonLines, user.avatarAuthenticate, user.numberAuthenticate) "
                    + "from TruckMessage message, Profile profile, User user where user.userId=profile.userId and message.userId=user.userId and message.userId=? ";
            inter = new TruckMessageInterceptor();
        } else {
            return null;
        }
        List<Object> list = new ArrayList<Object>();
        Long triggerTime = req.getAfter();
        if (triggerTime.equals(Long.MAX_VALUE)) {
            triggerTime = System.currentTimeMillis();
        }
        int count = req.getCount();
        //      for(int i = 0; i < Constant.SEARCH_TABLE_COUNT; i++) {
        Session session = null;
        try {
            inter.setShardCriteria(triggerTime);
            session = sessionFactory.openSession(inter);
            Query query = session.createQuery(hql + condition);
            query.setLong(0, userId);
            query.setLong(1, req.getBefore());
            query.setLong(2, req.getAfter());
            query.setFirstResult(0);
            query.setMaxResults(count);
            @SuppressWarnings("unchecked")
            List<Object> tmpList = query.list();
            if (tmpList != null && tmpList.size() > 0) {
                list.addAll(tmpList);
                if (tmpList.size() >= count) {
                    return list;
                }
                count -= tmpList.size();
                //               min = metaList.get(metaList.size() - 1).getUpdateTime();
            }
            if (inter.isFinishSearch(req.getBefore())) {
                return list;
            }
            triggerTime = inter.getTriggerTime();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (session != null) {
                session.close();
                session = null;
            }
        }
        //      }
        return list;
    }

    @Override
    public void updatePosition(PostPositionRequest req, long userId, Position user) {
        try {
            if (PositionHelper.distFrom(req.getLat(), req.getLon(), user.getLat(), user.getLon()) > 5000) {
                String hql = "update Position user set user.lon=?, user.lat=?, user.positionTime=?, user.city=?, "
                        + "user.lastEffectLon=?, user.lastEffectLat=?, user.lastPositionTime=?, user.lastEffectCity=?, "
                        + "user.updateTime=? ";
                hql += " where user.userId=?";
                Query query = sessionFactory.getCurrentSession().createQuery(hql);
                int i = 0;
                query.setDouble(i, req.getLon());
                query.setDouble(++i, req.getLat());
                query.setLong(++i, System.currentTimeMillis());
                query.setInteger(++i, req.getCityId());
                query.setDouble(++i, req.getLon());
                query.setDouble(++i, req.getLat());
                query.setLong(++i, System.currentTimeMillis());
                query.setInteger(++i, req.getCityId());
                query.setLong(++i, System.currentTimeMillis());
                query.setLong(++i, userId);
                query.executeUpdate();
            } else {
                String hql = "update Position user set user.lon=?, user.lat=?, user.positionTime=?, user.city=?, user.updateTime=? ";
                hql += " where user.userId=?";
                Query query = sessionFactory.getCurrentSession().createQuery(hql);
                int i = 0;
                query.setDouble(i, req.getLon());
                query.setDouble(++i, req.getLat());
                query.setLong(++i, System.currentTimeMillis());
                query.setInteger(++i, req.getCityId());
                query.setLong(++i, System.currentTimeMillis());
                query.setLong(++i, userId);
                query.executeUpdate();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public PasswordResponse findPasswordById(Long id) {
        try {
            Query query = sessionFactory.getCurrentSession().createQuery(
                    "select new com.consult.app.response.PasswordResponse(user.password, user.sessionId, user.announceTime, user.type) from User user where user.userId=?");
            query.setLong(0, id);
            return (PasswordResponse) query.uniqueResult();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public User findByIdFromDB(Long userId) {
        try {
            Query query = sessionFactory.getCurrentSession().createQuery("from User user where user.userId=?");
            query.setLong(0, userId);
            return (User) query.uniqueResult();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void clearToken(long userId, String token) {
        try {
            // Changed 20140429: For Send SMS to 
            //update User user set user.token='', user.sessionId=0 where user.userId=?
            String hql = "update User user set user.sessionId=0 where user.userId=?";
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setLong(0, userId);
            JUserCache.getInstance().removeUser(userId);
            query.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getOnlineUser(int cityId) {
        try {
            long onlineTriggerTime = TimeUtils.getStartOfDay(System.currentTimeMillis());// - Constant.HOUR_IN_MILLI;//PushExecutor.HEARTBEAT_INTERVAL * 2500;//1000*2.5
            //         String hql = "select new com.consult.app.response.user.LoginInfoItem(user.city, count(user.city)) " +
            //               "from User user, Profile profile " +
            //               "where user.userId=profile.userId and profile.userType=? and user.positionTime>? and user.city>0 " +
            //               "group by user.city";
            String hql = "select count(user.userId) " + "from User user, Profile profile "
                    + "where user.userId=profile.userId and profile.userType=? and user.updateTime>? and user.city=?";
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setInteger(0, Constant.USER_TYPE_TRUCKER);
            query.setLong(1, onlineTriggerTime);
            query.setInteger(2, cityId);
            return ((Long) query.uniqueResult()).intValue();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public List<Object> getLongUnloginUserToken(int appType, Long startId, int count, Long threshTime) {
        try {
            //         String content, Integer pushType, String token,
            //         Integer notificationType, int badgeCount
            String hql = "select new com.consult.app.push.modal.PushQueueItem('" + Constant.LONG_UNLOGIN_MSG_CONTENT
                    + "', user.loginFrom, user.token, " + PushUtil.NOTIFICATION_TYPE_BROADCAST + ", 0) "
                    + "from User user, Profile profile, Token token "
                    + "where user.userId=token.userId and user.token=token.token and user.userId=profile.userId and user.userId>? ";
            if (appType != Cookie.APP_TYPE_ALL) {
                hql = hql + " and user.loginFrom=? ";
            }
            hql = hql + " and profile.userType=? and user.lastLogin<? order by user.userId asc";
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            int i = 0;
            query.setLong(i, startId);
            if (appType != Cookie.APP_TYPE_ALL) {
                query.setInteger(++i, appType);
            }
            query.setInteger(++i, Constant.USER_TYPE_TRUCKER);
            query.setLong(++i, threshTime);
            query.setFirstResult(0);
            query.setMaxResults(count + 1);
            return query.list();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Object> getTodayLoginUsers(IdTypeBeforeAfterRequest req) {
        String hql = "";
        try {
            if (req.getId().intValue() <= Constant.CITY_ALL) {
                hql = "select new com.consult.app.response.admin.LastLoginItem(profile.userName, user.telephone, user.lastLogin) "
                        + "from User user, Profile profile "
                        + "where user.userId=profile.userId and user.lastLogin>? and user.lastLogin<? ";
                if (req.getType() == Constant.USER_TYPE_TRUCKER) {
                    hql = hql + " and profile.userType=?";
                } else {
                    hql = hql + " and profile.userType<>?";
                }
                hql = hql + " order by user.lastLogin desc";
                Query query = sessionFactory.getCurrentSession().createQuery(hql);
                //            query.setLong(0, TimeUtils.getStartOfDay(System.currentTimeMillis()));
                query.setLong(0, req.getBefore());
                query.setLong(1, req.getAfter());
                query.setInteger(2, Constant.USER_TYPE_TRUCKER);
                query.setFirstResult(0);
                query.setMaxResults(req.getCount());
                return query.list();
            } else {
                hql = "select new com.consult.app.response.admin.LastLoginItem(profile.userName, user.telephone, user.lastLogin) "
                        + "from User user, Profile profile "
                        + "where user.userId=profile.userId and user.lastLogin>? and user.lastLogin<? ";
                if (req.getType() == Constant.USER_TYPE_TRUCKER) {
                    hql = hql + " and profile.userType=?";
                } else {
                    hql = hql + " and profile.userType<>?";
                }
                hql = hql + " and user.city=? order by user.lastLogin desc";
                Query query = sessionFactory.getCurrentSession().createQuery(hql);
                query.setLong(0, req.getBefore());
                query.setLong(1, req.getAfter());
                query.setInteger(2, Constant.USER_TYPE_TRUCKER);
                query.setInteger(3, req.getId().intValue());
                query.setFirstResult(0);
                query.setMaxResults(req.getCount());
                return query.list();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //   @Override
    //   public void updateNewTruck(Truck truck) {
    //
    //      Session session = null;
    //      Transaction tx = null;
    //      try {
    //         String hql = "update Profile profile set profile.number=?, profile.truckLength=?, " +
    //         "profile.truckLoad=?, profile.truckType=?, profile.truckPicture=?, profile.commonLines=?, profile.updateTime=? where user.userId=?";
    //         session = sessionFactory.openSession();
    //         tx = session.beginTransaction();
    //         tx.setTimeout(Constant.TRANSCTION_TIMEOUT);
    //         Query query = session.createQuery(hql);
    //         query.setString(0, truck.getNumber());
    //         query.setDouble(1, truck.getTruckLength());
    //         query.setDouble(2, truck.getTruckLoad());
    //         query.setInteger(3, truck.getTruckType());
    //         query.setString(4, truck.getPicture());
    //         query.setString(5, truck.getCommonLines());
    //         query.setLong(6, System.currentTimeMillis());
    //         query.executeUpdate();
    //         tx.commit();
    //      } catch (Exception e) {
    //         e.printStackTrace();
    //         if(tx != null) {
    //            tx.rollback();
    //         }
    //      } finally {
    //         if(session != null) {
    //            session.close();
    //            session = null;
    //         }
    //      }
    //   }

    @Override
    public int updatePushConfig(TypeRequest req, long userId) {

        try {
            String hql = "update User user set user.pushSubscribe=? where user.userId=?";
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setInteger(0, req.getType());
            query.setLong(1, userId);
            if (query.executeUpdate() > 0) {
                JUserCache.getInstance().removeUser(userId);
            }
            return Cookie.RESPONSE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return Cookie.RESPONSE_SERVER_QUERY_ERROR;
        }

    }

    @Override
    public List<Object> getPreAuthenticateUsers(CountTypeRequest req) {
        String hql = "";
        List<Object> list1 = null, list2 = null;
        String cond = "";
        if (req.getType() == 1) {
            cond = " and profile.userType=1 ";
        } else if (req.getType() > 1) {
            cond = " and profile.userType>1 ";
        }
        try {
            //String userId, int type, String field1,
            //         String field2, Long updateTime, int userType
            hql = "select new com.consult.app.response.admin.AuthenticateUserItem("
                    + "user.userId, 1, cer.idCard, profile.picture, profile.companyName, profile.companyAddress, user.updateTime, profile.userType, user.telephone, cer.idNumber) "
                    + "from User user, Profile profile, Certificate cer "
                    + "where user.userId=profile.userId and user.certificateId=cer.userId "
                    + "and user.avatarAuthenticate=? and user.isAuthenticate=? " + cond
                    + " order by user.updateTime asc";
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setLong(0, Constant.USER_AUTHENTICATE_WAIT);
            query.setLong(1, Constant.USER_AUTHENTICATE_SUCCESS);
            query.setFirstResult(0);
            query.setMaxResults(req.getCount());
            return query.list();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        //      try {
        //         //String userId, int type, String field1,
        ////         String field2, Long updateTime, int userType
        //         hql = "select new com.consult.app.response.admin.AuthenticateUserItem(" +
        //         "user.userId, 2, profile.drivingLicense, profile.number, profile.companyName, profile.companyAddress, user.updateTime, profile.userType, user.telephone, '') " +
        //         "from User user, Profile profile " +
        //         "where user.userId=profile.userId " +
        //         "and user.numberAuthenticate=? order by user.updateTime asc";
        //         Query query = sessionFactory.getCurrentSession().createQuery(hql);
        //         query.setLong(0, Constant.USER_AUTHENTICATE_WAIT);
        //         query.setFirstResult(0);
        //         query.setMaxResults(req.getCount()); 
        //         list2 = query.list();
        //      } catch (Exception e) {
        //         e.printStackTrace();
        //         return null;
        //      }
        //      return Cookie.mergeSort(new ArrayList(list1), new ArrayList(list2), 20, Cookie.ORDER_ASC);
    }

    @Override
    public void updateAuthenticate(long userId, int status, int authType) {

        try {
            String hql = "";

            if (authType == Constant.AUDIT_TYPE_AVATAR) {
                hql = "update User user set user.avatarAuthenticate=?, user.updateTime=? where user.userId=?";
            } else if (authType == Constant.AUDIT_TYPE_DRIVING_LICENSE) {
                hql = "update User user set user.numberAuthenticate=?, user.updateTime=? where user.userId=?";
            } else if (authType == Constant.AUDIT_TYPE_IDNUMBER) {
                if (authType == Constant.USER_AUTHENTICATE_SUCCESS) {
                    hql = "update User user set user.isAuthenticate=?, user.updateTime=? where user.userId=?";
                } else {
                    hql = "update User user set user.isAuthenticate=?,user.avatarAuthenticate=0,user.updateTime=? where user.userId=?";
                }
            }
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setLong(0, status);
            query.setLong(1, System.currentTimeMillis());
            query.setLong(2, userId);
            if (query.executeUpdate() > 0) {
                JUserCache.getInstance().removeUser(userId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public MessageAuthenticateItem getMessageAuthenticate(Long userId) {

        try {
            //int avatarAuthenticate,
            //         int numberAuthenticate, String picture
            String hql = "select new com.consult.app.response.user.MessageAuthenticateItem("
                    + "user.userId, user.avatarAuthenticate, user.numberAuthenticate, profile.picture) "
                    + "from User user, Profile profile " + "where user.userId=profile.userId and user.userId=?";
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setLong(0, userId);
            return (MessageAuthenticateItem) query.uniqueResult();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Object> getPreIdAuthenticateUsers(CountRequest req) {
        try {
            //String userId, int type, String field1,
            //         String field2, Long updateTime, int userType
            String hql = "select new com.consult.app.response.admin.AuthenticateUserItem("
                    + "user.userId, 3, certificate.idNumber, certificate.realName, user.updateTime, profile.userType, user.telephone) "
                    + "from User user, Certificate certificate, Profile profile "
                    + "where user.userId=profile.userId and user.certificateId=certificate.userId "
                    + "and user.isAuthenticate=? order by user.userId asc";
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setLong(0, Constant.USER_AUTHENTICATE_WAIT);
            query.setFirstResult(0);
            query.setMaxResults(req.getCount());
            return query.list();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public CargoMessageAuthItem getMessageAuthenticateByTel(Long telephone) {

        try {
            //int avatarAuthenticate,
            //         int numberAuthenticate, String picture
            String hql = "select new com.consult.app.response.user.CargoMessageAuthItem("
                    + "user.userId, user.avatarAuthenticate, user.numberAuthenticate, profile.picture, profile.companyName,"
                    + "profile.companyAddress, profile.userName, profile.landlines, profile.userType, profile.score, profile.orderCount, profile.messageCount, user.installPlace) "
                    + "from User user, Profile profile " + "where user.userId=profile.userId and user.telephone=?";
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setLong(0, telephone);
            return (CargoMessageAuthItem) query.uniqueResult();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Integer getLoginCount(int userType, long from, long to) {
        try {
            String hql = "";
            if (userType == Constant.USER_TYPE_TRUCKER) {
                hql = "select count(*) from User user, Profile profile where user.userId=profile.userId and user.lastLogin>? and user.lastLogin<? and profile.userType=?";
            } else {
                hql = "select count(*) from User user, Profile profile where user.userId=profile.userId and user.lastLogin>? and user.lastLogin<? and profile.userType>=?";
            }
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setLong(0, from);
            query.setLong(1, to);
            query.setInteger(2, userType);
            return ((Long) query.uniqueResult()).intValue();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public List<Object> getLongUnloginUserTelephone(int appType, Long startId, int count, Long threshTime) {
        try {
            //         String content, Integer pushType, String token,
            //         Integer notificationType, int badgeCount
            String hql = "select new com.consult.app.response.user.TelephoneItem(user.telephone) "
                    + "from User user, Token token "
                    + "where user.userId=token.userId and user.token=token.token and user.userId>? ";
            if (appType != Cookie.APP_TYPE_ALL) {
                hql = hql + " and user.loginFrom=? ";
            }
            hql = hql + " and profile.userType=? and user.lastLogin<? order by user.userId asc";
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            int i = 0;
            query.setLong(i, startId);
            if (appType != Cookie.APP_TYPE_ALL) {
                query.setInteger(++i, appType);
            }
            query.setInteger(++i, Constant.USER_TYPE_TRUCKER);
            query.setLong(++i, threshTime);
            query.setFirstResult(0);
            query.setMaxResults(count + 1);
            return query.list();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int getRegisterCount(int userType, long from, long to, int city) {
        try {
            String hql = "";
            if (userType == Constant.USER_TYPE_TRUCKER) {
                hql = "select count(*) from User user, Profile profile  where user.userId=profile.userId and user.createTime>? and user.createTime<? and profile.userType=?";
            } else {
                hql = "select count(*) from User user, Profile profile  where user.userId=profile.userId and user.createTime>? and user.createTime<? and profile.userType>=?";
            }
            if (city > 0) {
                hql = hql + " and user.installPlace=?";
            }
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setLong(0, from);
            query.setLong(1, to);
            query.setInteger(2, userType);
            if (city > 0) {
                query.setInteger(3, city);
            }
            return ((Long) query.uniqueResult()).intValue();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    //   @Override
    //   public void updatePositionAndSmsLocate(PostPositionRequest req,
    //         Long userId, User user) {
    //
    //      try {
    //         if(PositionHelper.distFrom(req.getLat(), req.getLon(), user.getLat(), user.getLon()) > 5000) {
    //            String hql = "update User user set user.lon=?, user.lat=?, user.positionTime=?, user.city=?, " +
    //                  "user.lastEffectLon=?, user.lastEffectLat=?, user.lastPositionTime=?, user.lastEffectCity=?, user.smsLocate=? ";
    //            if(user.getInstallPlace() <= 0) {
    //               hql = hql + " , user.installPlace=? ";
    //            }
    //            hql += " where user.userId=?";
    //            Query query = sessionFactory.getCurrentSession().createQuery(hql);
    //            int i = 0;
    //            query.setDouble(i, req.getLon());
    //            query.setDouble(++i, req.getLat());
    //            query.setLong(++i, System.currentTimeMillis());
    //            query.setInteger(++i, req.getCityId());
    //            query.setDouble(++i, req.getLon());
    //            query.setDouble(++i, req.getLat());
    //            query.setLong(++i, System.currentTimeMillis());
    //            query.setInteger(++i, req.getCityId());
    //            query.setInteger(++i, Constant.SMS_LOCATE_SUCCESS);
    //            if(user.getInstallPlace() <= 0) {
    //               query.setInteger(++i, Integer.valueOf(req.getCityId() / 100) * 100);
    //            }
    //            query.setLong(++i, userId);
    //            query.executeUpdate();
    //         } else {
    //            String hql = "update User user set user.lon=?, user.lat=?, user.positionTime=?, user.city=?, user.smsLocate=? ";
    //            if(user.getInstallPlace() <= 0) {
    //               hql = hql + " , user.installPlace=? ";
    //            }
    //            hql += " where user.userId=?";
    //            Query query = sessionFactory.getCurrentSession().createQuery(hql);
    //            int i = 0;
    //            query.setDouble(i, req.getLon());
    //            query.setDouble(++i, req.getLat());
    //            query.setLong(++i, System.currentTimeMillis());
    //            query.setInteger(++i, req.getCityId());
    //            query.setInteger(++i, Constant.SMS_LOCATE_SUCCESS);
    //            if(user.getInstallPlace() <= 0) {
    //               query.setInteger(++i, Integer.valueOf(req.getCityId() / 100) * 100);
    //            }
    //            query.setLong(++i, userId);
    //            query.executeUpdate();
    //         }
    //      } catch (Exception e) {
    //         e.printStackTrace();
    //      }
    //   
    //   }

    @Override
    public List<Object> getReadyToCheckUser(Long startId, int count) {

        try {
            //         String content, Integer pushType, String token,
            //         Integer notificationType, int badgeCount
            String hql = "from User user " + "where user.userId>? and user.smsLocate=? order by user.userId asc";
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setLong(0, startId);
            query.setInteger(1, Constant.SMS_LOCATE_READY_TO_CHECK);
            query.setFirstResult(0);
            query.setMaxResults(count + 1);
            return query.list();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
    //
    //   @Override
    //   public void updateSmsLocateState(int smsLocate, Long userId) {
    //
    //      try {
    //         String hql = "update User user set user.smsLocate=?, user.updateTime=? where user.userId=?";
    //         Query query = sessionFactory.getCurrentSession().createQuery(hql);
    //         query.setInteger(0, smsLocate);
    //         query.setLong(1, System.currentTimeMillis());
    //         query.setLong(2, userId);
    //         query.executeUpdate();
    //      } catch (Exception e) {
    //         e.printStackTrace();
    //      }
    //      
    //   }

    @Override
    public void disableSms(Long userId, int trigger) {
        try {
            Query query = sessionFactory.getCurrentSession()
                    .createQuery("update User obj set obj.pushSubscribe=? where obj.userId=?");
            query.setInteger(0, trigger);
            query.setLong(1, userId);
            if (query.executeUpdate() > 0) {
                JUserCache.getInstance().removeUser(userId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void reAuthenticate(Long userId) {

        try {
            Query query = sessionFactory.getCurrentSession()
                    .createQuery("update User set avatarAuthenticate=0, updateTime=? where userId=?");
            query.setLong(0, System.currentTimeMillis());
            query.setLong(1, userId);
            if (query.executeUpdate() > 0) {
                JUserCache.getInstance().removeUser(userId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void changeTelephone(Long userId, Long telephone) {

        try {
            Query query = sessionFactory.getCurrentSession()
                    .createQuery("update User obj set obj.telephone=? where obj.userId=?");
            query.setLong(0, telephone);
            query.setLong(1, userId);
            if (query.executeUpdate() > 0) {
                JUserCache.getInstance().removeUser(userId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public RegisterResponse registerVerify(Long userId, RegisterRequest req, int smsLocate, long smsLocateInterval,
            UnregisterUser unUser) {
        RegisterResponse rp = new RegisterResponse(Cookie.RESPONSE_SUCCESS);
        long now = System.currentTimeMillis();
        Long sessionId = Math.abs(RandomNumber.createRandomLong());
        String password = MessageDigestGenerator
                .generateSHA256(MessageDigestGenerator.generateSHA256(sessionId.toString()));
        User user = new User(userId, req.getVersion(), password, req.getFrom(), Long.valueOf(req.getTelephone()),
                now, now, req.getToken(), now, sessionId, Constant.USER_UNAUTHENTICATE);
        sessionFactory.getCurrentSession().save(user);
        Position position = new Position(user.getUserId(), now, smsLocate, now + smsLocateInterval);
        if (unUser != null) {
            position.setCreateTime(unUser.getCreateTime());
            position.setPositionTime(unUser.getPositionTime());
            position.setSmsLocate(unUser.getSmsLocate());
        }
        sessionFactory.getCurrentSession().save(position);
        Profile profile = new Profile();
        profile.setUserName(user.getTelephone().toString());
        profile.setUserId(user.getUserId());
        profile.setUserType(req.getUserType());
        profile.setUpdateTime(now);
        profile.setCreateTime(now);
        if (unUser != null) {
            profile.setOrderCount(unUser.getOrderCount());
            profile.setScore(unUser.getScore());
            profile.setCommentCount(unUser.getCommentCount());
        }
        sessionFactory.getCurrentSession().save(profile);
        rp.setIsAuthenticate(Constant.USER_UNAUTHENTICATE);
        rp.setSessionId(user.getSessionId().toString());
        rp.setResult(Cookie.RESPONSE_SUCCESS);
        rp.setId(user.getUserId());
        rp.setPushSubscribe(user.getPushSubscribe());
        rp.setStrId(String.valueOf(user.getUserId()));
        rp.setToken(MessageDigestGenerator.generateSHA256(sessionId.toString()));
        rp.setHeartBeat(ConfigUtil.getInstance().getHeartbeatInterval());
        return rp;
    }

    @Override
    public int isTelephoneExist(Long telephone) {
        try {
            Query query = sessionFactory.getCurrentSession().createQuery("from User user where user.telephone=?");
            query.setLong(0, telephone);
            List<Object> list = query.list();
            if (list == null || list.isEmpty()) {
                return 0;
            }
            return list.size();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public void setIdNumberAuthenticated(Long userId, Long certificateId, int auth) {

        try {
            String hql = "update User user set user.isAuthenticate=?, user.updateTime=?, user.certificateId=? where user.userId=?";
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setLong(0, auth);
            query.setLong(1, System.currentTimeMillis());
            query.setLong(2, certificateId);
            query.setLong(3, userId);
            if (query.executeUpdate() > 0) {
                JUserCache.getInstance().removeUser(userId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        long today = TimeUtils.getStartOfDay(System.currentTimeMillis());
        System.out.print(today);
    }

    @Override
    public void updateLastLogin(long userId) {
        try {
            String hql = "update User user set user.lastLogin=?, user.updateTime=? where user.userId=?";
            Query query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setLong(0, System.currentTimeMillis());
            query.setLong(1, System.currentTimeMillis());
            query.setLong(2, userId);
            if (query.executeUpdate() > 0) {
                //            JUserCache.getInstance().removeUser(userId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<Object> searchDriverList(SearchDriverRequest req) {
        /**
         * 
         */
        long possitionTime = System.currentTimeMillis() - TimeUtils.DAY * 14;
        Query query = null;
        StringBuffer querysql = new StringBuffer("");
        String truckLengthCondition = req.getTruckLength() <= 0d ? "" : "and p.truck_length=:truckLength";
        String sqlTem = "(select u.user_id as userId,p.picture as picture,p.user_name as userName,u.telephone as telephone,p.truck_length as truckLength,p.truck_load as truckLoad,p.truck_type as truckType,p.number as number,u.is_authenticate as isAuthenticate,u.create_time as updateTime,p.order_count as orderCount,u.city as cityId,abs(u.city-:start) as sortFlag from users u, profiles p, %s sub, search_conditions sc where sub.user_id=u.user_id and u.user_id=p.user_id and p.user_type=1 and sub.search_id=sc.search_id and u.telephone>13000000000 "
                + truckLengthCondition
                + " and sub.push_subscribe=1 and u.push_subscribe=1 and u.type=1 and sub.type>0 and (sc.end=:end or sc.end=:endFather) and (sc.start=:start or sc.start=:startFather) and u.update_time>:before and u.update_time<:after and u.update_time>:possitionTime)";
        for (int i = 0; i < Constant.SHARD_TABLE_SUBSCRIBE.length; i++) {
            if (i == 0) {
                querysql.append("select t.* from (" + String.format(sqlTem, Constant.SHARD_TABLE_SUBSCRIBE[i])
                        + " union all ");
            } else if (i == Constant.SHARD_TABLE_SUBSCRIBE.length - 1) {
                querysql.append(String.format(sqlTem, Constant.SHARD_TABLE_SUBSCRIBE[i])
                        + ") t group by t.userId order by t.sortFlag asc,t.updateTime desc");//,t.orderCount desc
            } else {
                querysql.append(String.format(sqlTem, Constant.SHARD_TABLE_SUBSCRIBE[i]) + " union all ");
            }
        }

        query = sessionFactory.getCurrentSession().createSQLQuery(querysql.toString())
                .addScalar("userId", StandardBasicTypes.LONG).addScalar("picture", StandardBasicTypes.STRING)
                .addScalar("userName", StandardBasicTypes.STRING).addScalar("telephone", StandardBasicTypes.STRING)
                .addScalar("truckLength", StandardBasicTypes.DOUBLE)
                .addScalar("truckLoad", StandardBasicTypes.DOUBLE)
                .addScalar("truckType", StandardBasicTypes.INTEGER).addScalar("number", StandardBasicTypes.STRING)
                .addScalar("isAuthenticate", StandardBasicTypes.INTEGER)
                .addScalar("updateTime", StandardBasicTypes.LONG)
                .addScalar("orderCount", StandardBasicTypes.INTEGER).addScalar("cityId", StandardBasicTypes.INTEGER)
                .setResultTransformer(Transformers.aliasToBean(com.consult.app.response.truck.DriverInfo.class));
        if (req.getTruckLength() > 0) {
            query.setDouble("truckLength", req.getTruckLength());
        }
        query.setInteger("end", req.getEnd()).setInteger("endFather", req.getEndFather())
                .setInteger("start", req.getStart()).setInteger("startFather", req.getStartFather())
                .setLong("before", req.getBefore()).setLong("after", req.getAfter())
                .setLong("possitionTime", possitionTime);
        query.setMaxResults(req.getCount());
        @SuppressWarnings("unchecked")
        List<Object> all = query.list();
        return all;
    }

    public Object findDriverByTelephone(Long telephone) {
        Object obj = null;
        try {
            String sql = "select '1'as userType,u.user_id as userId,p.picture as picture,p.user_name as userName,u.telephone as telephone,p.truck_length as truckLength,p.truck_load as truckLoad,p.truck_type as truckType,p.number as number,u.is_authenticate as isAuthenticate from users u, profiles p where  u.user_id=p.user_id and p.user_type=1 and  u.telephone=? ";
            Query query = null;
            query = sessionFactory.getCurrentSession().createSQLQuery(sql)
                    .addScalar("userType", StandardBasicTypes.INTEGER).addScalar("userId", StandardBasicTypes.LONG)
                    .addScalar("picture", StandardBasicTypes.STRING)
                    .addScalar("userName", StandardBasicTypes.STRING)
                    .addScalar("telephone", StandardBasicTypes.STRING)
                    .addScalar("truckLength", StandardBasicTypes.DOUBLE)
                    .addScalar("truckLoad", StandardBasicTypes.DOUBLE)
                    .addScalar("truckType", StandardBasicTypes.INTEGER)
                    .addScalar("number", StandardBasicTypes.STRING)
                    .addScalar("isAuthenticate", StandardBasicTypes.INTEGER)
                    .setResultTransformer(Transformers.aliasToBean(com.consult.app.response.truck.DriverInfo.class))
                    .setLong(0, telephone);
            obj = query.uniqueResult();
            if (obj == null) {
                sql = "select  '0' as userType, u.user_id as userId,'' as picture,u.user_name as userName,u.telephone as telephone,u.truck_length as truckLength,u.truck_load as truckLoad,u.truck_type as truckType,u.truck_number as number,0 as isAuthenticate from unregister_user u where   u.type=2 and  u.telephone=?";
                query = sessionFactory.getCurrentSession().createSQLQuery(sql)
                        .addScalar("userType", StandardBasicTypes.INTEGER)
                        .addScalar("userId", StandardBasicTypes.LONG)
                        .addScalar("picture", StandardBasicTypes.STRING)
                        .addScalar("userName", StandardBasicTypes.STRING)
                        .addScalar("telephone", StandardBasicTypes.STRING)
                        .addScalar("truckLength", StandardBasicTypes.DOUBLE)
                        .addScalar("truckLoad", StandardBasicTypes.DOUBLE)
                        .addScalar("truckType", StandardBasicTypes.INTEGER)
                        .addScalar("number", StandardBasicTypes.STRING)
                        .addScalar("isAuthenticate", StandardBasicTypes.INTEGER)
                        .setResultTransformer(
                                Transformers.aliasToBean(com.consult.app.response.truck.DriverInfo.class))
                        .setLong(0, telephone);
                obj = query.uniqueResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    public Object findDriverByUserId(Long id) {
        Object obj = null;
        try {
            String sql = "select '1'as userType,u.user_id as userId,p.picture as picture,p.user_name as userName,u.telephone as telephone,p.truck_length as truckLength,p.truck_load as truckLoad,p.truck_type as truckType,p.number as number,u.is_authenticate as isAuthenticate from users u, profiles p where  u.user_id=p.user_id and p.user_type=1 and  u.user_id=? ";
            Query query = null;
            query = sessionFactory.getCurrentSession().createSQLQuery(sql)
                    .addScalar("userType", StandardBasicTypes.INTEGER).addScalar("userId", StandardBasicTypes.LONG)
                    .addScalar("picture", StandardBasicTypes.STRING)
                    .addScalar("userName", StandardBasicTypes.STRING)
                    .addScalar("telephone", StandardBasicTypes.STRING)
                    .addScalar("truckLength", StandardBasicTypes.DOUBLE)
                    .addScalar("truckLoad", StandardBasicTypes.DOUBLE)
                    .addScalar("truckType", StandardBasicTypes.INTEGER)
                    .addScalar("number", StandardBasicTypes.STRING)
                    .addScalar("isAuthenticate", StandardBasicTypes.INTEGER)
                    .setResultTransformer(Transformers.aliasToBean(com.consult.app.response.truck.DriverInfo.class))
                    .setLong(0, id);
            obj = query.uniqueResult();
            if (obj == null) {
                sql = "select  '0' as userType, u.user_id as userId,'' as picture,u.user_name as userName,u.telephone as telephone,u.truck_length as truckLength,u.truck_load as truckLoad,u.truck_type as truckType,u.truck_number as number,0 as isAuthenticate from unregister_user u where   u.type=2 and  u.user_id=?";
                query = sessionFactory.getCurrentSession().createSQLQuery(sql)
                        .addScalar("userType", StandardBasicTypes.INTEGER)
                        .addScalar("userId", StandardBasicTypes.LONG)
                        .addScalar("picture", StandardBasicTypes.STRING)
                        .addScalar("userName", StandardBasicTypes.STRING)
                        .addScalar("telephone", StandardBasicTypes.STRING)
                        .addScalar("truckLength", StandardBasicTypes.DOUBLE)
                        .addScalar("truckLoad", StandardBasicTypes.DOUBLE)
                        .addScalar("truckType", StandardBasicTypes.INTEGER)
                        .addScalar("number", StandardBasicTypes.STRING)
                        .addScalar("isAuthenticate", StandardBasicTypes.INTEGER)
                        .setResultTransformer(
                                Transformers.aliasToBean(com.consult.app.response.truck.DriverInfo.class))
                        .setLong(0, id);
                obj = query.uniqueResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    @Override
    public List<Object> getWhiteTable(Long updateTime) {
        Query query = sessionFactory.getCurrentSession().createQuery("from WhiteList l where l.updateTime>?");
        query.setLong(0, updateTime);
        return query.list();
    }

}