Subversion Repositories SmartDukaan

Rev

Blame | Last modification | View Log | RSS feed

package in.shop2020.serving.services;

import in.shop2020.model.v1.user.Cart;
import in.shop2020.model.v1.user.User;
import in.shop2020.model.v1.user.UserContextException;
import in.shop2020.serving.interceptors.UserInterceptor;
import in.shop2020.serving.utils.DesEncrypter;
import in.shop2020.thrift.clients.UserClient;

import java.io.Serializable;

import org.apache.log4j.Logger;
import org.apache.thrift.TException;

import com.google.gson.Gson;

/**
 * This class is used to cache data that is frequently accessed for displaying
 * on the pages of the site. It implements Serializable since
 * <a href="http://tomcat.apache.org/tomcat-5.5-doc/config/manager.html#Restart%20Persistence">Tomcat's restart persistence</a>
 * ensures that all session attributes will be preserved across application
 * restarts.
 * 
 * @author Chandranshu
 * 
 */
@SuppressWarnings("serial")
public class UserSessionInfo implements Serializable{
    
    private static Logger logger = Logger.getLogger(UserSessionInfo.class);
    
        /**
         * 
         */
        private boolean isLoggedIn;
        private long userId;
        private String email;
        private int totalItems;
        private long cartId;
        private String pincode;
        private double totalAmount;
        
        public UserSessionInfo(){
                this.isLoggedIn = false;
                this.userId = -1;
                this.email = "";
                this.totalItems = 0;
                this.cartId = -1;
                this.pincode = "110001";
                this.totalAmount = 0;
        }

        public UserSessionInfo(long userId, String jsessionId){
                this();
                try {
                    UserClient ucsc = new UserClient();
                    in.shop2020.model.v1.user.UserContextService.Client userClient = ucsc.getClient();
                    User existingUser = userClient.getUserById(userId);
                        if(existingUser != null && existingUser.getUserId() != -1){
                                Cart cart = userClient.getCart(existingUser.getActiveCartId());
                        totalItems = cart.getLinesSize();
                        totalAmount = cart.getTotalPrice();
                        pincode = userClient.getDefaultPincode(existingUser.getUserId());
                        initialize(existingUser, totalItems, pincode, totalAmount);
                        }
                } catch (UserContextException e) {
                    logger.error("Unable to get user info from user service: ", e);
                } catch (TException e) {
                    logger.error("Unable to get user info from user service: ", e);
                } catch (Exception e) {
                    logger.error("Unexpected exception: ", e);
                }       
        }

        public UserSessionInfo(String jsessionId) {
                this();
                UserClient ucsc = null;
                try {
                        ucsc = new UserClient();
                        in.shop2020.model.v1.user.UserContextService.Client userClient = ucsc.getClient();
                        User anonUser = userClient.createAnonymousUser(jsessionId);
                        Cart cart = userClient.getCart(anonUser.getActiveCartId());
                        int totalItems = cart.getLinesSize();
                        double totalAmount = cart.getTotalPrice();
                        pincode = userClient.getDefaultPincode(anonUser.getUserId());
                        initialize(anonUser, totalItems, pincode, totalAmount);
                } catch (UserContextException e) {
                    logger.error("Unable to get user info from user service: ", e);
                } catch (TException e) {
                    logger.error("Unable to get user info from user service: ", e);
                } catch (Exception e) {
                    logger.error("Unexpected exception: ", e);
                }
        }

        private void initialize(User user, int totalItems, String pincode, double totalAmount){
                if(user!=null){
                        this.isLoggedIn = !user.isIsAnonymous();
                        this.userId = user.getUserId();
                        this.email = user.getEmail();
                        this.cartId = user.getActiveCartId();
                        this.totalItems = totalItems;
                        this.pincode = pincode;
                        this.totalAmount = totalAmount;
                }else{
                        this.isLoggedIn = false;
                        this.userId = -1;
                        this.email = "";
                        this.totalItems = 0;
                        this.cartId = -1;
                        this.pincode = pincode;
                        this.totalAmount = 0;
                }                       
        }
        
        public boolean isSessionId() {
                return !isLoggedIn;
        }

        public boolean isLoggedIn() {
                return isLoggedIn;
        }

        public void setLoggedIn(boolean isLoggedIn) {
                this.isLoggedIn = isLoggedIn;
        }

        public long getUserId() {
                return userId;
        }

        public void setUserId(long userId) {
                this.userId = userId;
        }

        public String getEmail() {
                return email;
        }

        public void setEmail(String email) {
                this.email = email;
        }
        
        public int getTotalItems() {
                return totalItems;
        }

        public void setTotalItems(int totalItems) {
                this.totalItems = totalItems;
        }
        public long getCartId() {
                return cartId;
        }

        public void setCartId(long cartId) {
                this.cartId = cartId;
        }       

        public String getPincode() {
                return pincode;
        }

        public void setPincode(String pincode) {
                this.pincode = pincode;
        }

        public void setTotalAmount(double totalAmount) {
                this.totalAmount = totalAmount;
        }

        public double getTotalAmount() {
                return totalAmount;
        }
        
        public static String getUserinfoCookieValueFromUserSessionInfo(UserSessionInfo userinfo){
                DesEncrypter desEncrypter = new DesEncrypter(UserInterceptor.COOKIE_DECRYPTION_STRING);
                Gson gson = new Gson();
                return desEncrypter.encrypt(gson.toJson(userinfo));
        }
        
        public static UserSessionInfo getUserSessionInfoFromCookieValue(String jsonString){
                DesEncrypter desEncrypter = new DesEncrypter(UserInterceptor.COOKIE_DECRYPTION_STRING);
                Gson gson = new Gson();
                UserSessionInfo userinfo = null;
                try{
                        userinfo = gson.fromJson(desEncrypter.decrypt(jsonString), UserSessionInfo.class);
                        //As we are adding a new field in the cookie. So to populate this field for existing users
                        if(userinfo.getTotalAmount() == 0 && userinfo.getTotalItems() != 0 ){
                                try {
                                        UserClient ucsc = new UserClient();
                                        in.shop2020.model.v1.user.UserContextService.Client userClient = ucsc.getClient();
                                        Cart cart = userClient.getCart(userinfo.getCartId());
                                        userinfo.setTotalItems(cart.getLinesSize());
                                        userinfo.setTotalAmount(cart.getTotalPrice());
                                }catch (Exception e) {
                                        logger.error("Unable to update total amount in userinfo object from database.", e);             
                                }
                        }
                }catch (Exception e) {
                    logger.error("Unable to get the userinfo object from the JSON string because of", e);
                }
                if(userinfo==null){
                    userinfo = new UserSessionInfo();
                }
                return userinfo;
        }
        
        @Override
        public String toString() {
                return "UserSessionInfo [isLoggedIn=" + isLoggedIn + ", userId=" + userId + ", email=" + email
                                + ", totalItems=" + totalItems + ", cartId=" + cartId
                                + ", pincode=" + pincode + ", totalAmount=" + totalAmount + "]";
        }

        public static void main(String[] args) {
                System.out.println();
                String cookieValue = "fG0CKt4DUD_D9iP1Ero0v2Io1AgVLoGqXDp0NWAPkzZuw3zHKot5owJK6IodZQfE2aS-obOK3BwXUNRirVHDyd-ycsyG4GfBPd0Ypl1MkxuVBmY4csB0FEg_IgWUm9GaGEzvtmmiZ5bE24XlpUPqR4AoTUAp8d92DDTG61FOFktDIGg3L0Tyk4qpVlAU3xQ3";
                UserSessionInfo uinfo = UserSessionInfo.getUserSessionInfoFromCookieValue(cookieValue);
                System.out.println(uinfo);
        }
}