Subversion Repositories SmartDukaan

Rev

Rev 20185 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.serving.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.net.ssl.HttpsURLConnection;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;

import in.shop2020.config.ConfigException;
import in.shop2020.model.v1.catalog.ExclusiveAffiliateItemInfo;
import in.shop2020.model.v1.order.LineItem;
import in.shop2020.model.v1.order.Order;
import in.shop2020.model.v1.order.RechargeOrderStatus;
import in.shop2020.model.v1.order.RechargePlan;
import in.shop2020.model.v1.order.RechargeType;
import in.shop2020.model.v1.user.Cart;
import in.shop2020.model.v1.user.Line;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.config.ConfigClient;

public class Utils {
    private static Logger logger = Logger.getLogger(Utils.class);
    
        public static final String EXPORT_ENTITIES_PATH = getExportPath();
        public static final String EXPORT_JAVASCRIPT_CONTENT_PATH = "/var/lib/tomcat6/webapps/export/javascripts/";
        public static final long ROOT_CATEGORY = 10000;
        public static final long MOBILE_PHONES_CATEGORY = 10001;
        public static final long MOBILE_ACCESSORIES_CATEGORY = 10011;
        public static final long TABLETS_CATEGORY = 10010;
    public static final long LAPTOPS_CATEGORY = 10050;
    public static final long CAMERAS_CATEGORY = 11001;
    
    static Map<Long, String> providersMap;
    static Map<Long, String> mobileProvidersMap;
    static Map<Long, String> dthProvidersMap;
    static Map<Long, ExclusiveAffiliateItemInfo> exclusiveAffiliateItems = null;
    static Map<Long, List<RechargePlan>> operatorPlanMap = new HashMap<Long, List<RechargePlan>>(); 
    private static Map<String, Map<String, String>> uriOperatorMap = new HashMap<String, Map<String,String>>();
    static long fifteenMinsCounter = 0l; 
    
    public static final List<RechargeOrderStatus> refundableRechargeStatusList = new ArrayList<RechargeOrderStatus>(Arrays.asList(new RechargeOrderStatus[] 
                                                                                                                                                     {RechargeOrderStatus.RECHARGE_FAILED, 
                                                                                                                                                      RechargeOrderStatus.RECHARGE_FAILED_REFUNDED}));
    
    public static Map<RechargeOrderStatus, String> statusMap = new HashMap<RechargeOrderStatus, String>();
    
    //public static final List<String> multiValuedFacet = Arrays.asList("F_50006");
    
    public static final  List<String>rootfacetDefIDs = Arrays.asList("F_50010","F_50011","F_50002", "F_50001", "F_50028");
    public static final  String availabilityFacet = "F_50028";
        public static final Map<String, String> FACET_LABEL_MAP = Collections.unmodifiableMap(
                        new HashMap<String, String>(){
                                /**
                                 * 
                                 */
                                private static final long serialVersionUID = 1L;

                                {
                                        put("F_50010","Category");
                                        put("F_50011","Sub Category");
                                        put("F_50002","Price");
                                        put("F_50001","Brand");
                                        put("F_50006","Data Connectivity");
                                        put("F_50007","Camera Resolution");
                                        put("F_50039","");
                                        put("F_50012","Display");
                                        put("F_50013","Operating System");
                                        put("F_50014","RAM");
                                        put("F_50015","Storage Capacity");
                                        put("F_50017","Processor");
                                        put("F_50018","Capacity");
                                        put("F_50019","Class");
                                        put("F_50020","Capacity");
                                        put("F_50021","Capacity");
                                        put("F_50022","Type");
                                        put("F_50023","Interface");
                                        //Resolution for Composite
                                        put("F_50024","Resolution");
                                        put("F_50025","Optical Zoom");
                                        put("F_50026","Display Size");
                                        //Resolution for DSLR
                                        put("F_50027","Resolution");
                                        put("F_50028","Availability");
                                        put("F_50031","Operating System");
                                        put("F_50032","Screen Size");   //Screen size for mobiles
                                        put("F_50033","Screen Size");   //Screen size for laptop
                                        put("F_50034","Screen Size");   //Screen size for tablets
                                        put("F_50035","Operating System");      //Screen size for tablets
                                        put("F_50036","Camera Resolution");     //Screen size for tablets
                                        put("F_50037","Voice Call Facility");   //Screen size for tablets
                                        put("F_50038","Mobile Type");   //Mobile Type
                                        put("F_50028","Availability");
                                }
                });
    
    static {
        statusMap.put(RechargeOrderStatus.PAYMENT_FAILED, "Payment Unsuccessful");
        statusMap.put(RechargeOrderStatus.PAYMENT_SUCCESSFUL, "Processing Recharge");
        statusMap.put(RechargeOrderStatus.RECHARGE_FAILED, "Recharge Failed");
        statusMap.put(RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, "Recharge Failed");
        statusMap.put(RechargeOrderStatus.RECHARGE_SUCCESSFUL, "Recharge Successful");
        statusMap.put(RechargeOrderStatus.REFUNDED, "Amount Refunded");
        statusMap.put(RechargeOrderStatus.PARTIALLY_REFUNDED, "Amount Refunded");
        
        TransactionClient tcl;
        try {
            tcl = new TransactionClient();
            mobileProvidersMap = tcl.getClient().getServiceProviders(RechargeType.MOBILE, true);
            dthProvidersMap = tcl.getClient().getServiceProviders(RechargeType.DTH, true);
//            providersMap.putAll(mobileProvidersMap);
//            providersMap.putAll(dthProvidersMap);
            for (Long operatorId : mobileProvidersMap.keySet()) {
                List<RechargePlan> plans = tcl.getClient().getPlansForOperator(operatorId);
                if (!plans.isEmpty()) {
                    operatorPlanMap.put(operatorId, plans);
                }
            }
            for (Long operatorId : mobileProvidersMap.keySet()) {
                Map<String,String> valueMap = new HashMap<String,String>();
                valueMap.put("Id", operatorId+"");
                valueMap.put("Name", mobileProvidersMap.get(operatorId)+"");
                valueMap.put("ServiceType", "1");
                valueMap.put("ServiceName", "Prepaid Mobile");
                uriOperatorMap.put(mobileProvidersMap.get(operatorId).toLowerCase().trim().replace(" ", "-")+"-online-recharge", valueMap);
            }
            for (Long operatorId : dthProvidersMap.keySet()) {
                Map<String,String> valueMap = new HashMap<String,String>();
                valueMap.put("Id", operatorId+"");
                valueMap.put("Name", dthProvidersMap.get(operatorId)+"");
                valueMap.put("ServiceType", "2");
                valueMap.put("ServiceName", "DTH TV");
                uriOperatorMap.put(dthProvidersMap.get(operatorId).toLowerCase().trim().replace(" ", "-")+"-online-recharge", valueMap);
            }
            
            Map<String,String> valueMap = new HashMap<String,String>();
            valueMap.put("Id", "0");
                valueMap.put("Name", "Mobile and DTH");
                valueMap.put("ServiceType", "1");
                valueMap.put("ServiceName", "");
                uriOperatorMap.put("recharge", valueMap);
//            providersMap.putAll(tcl.getClient().getServiceProviders(RechargeType.DTH));
                
                
        } catch (Exception e) {
            logger.error("Could not get providers", e);
        }
    }
    
    
    
        private static String getExportPath(){
                String exportPath=null;
                ConfigClient client = ConfigClient.getClient();
                try{
                        exportPath = client.get("export_entities_path");
                }catch(ConfigException ce){
                        logger.error("Unable to read export path from the config client: ", ce);
                        logger.warn("Setting the default export path");
                        exportPath = "/var/lib/tomcat6/webapps/export/html/entities/";
                }
                return exportPath;
        }
        
        
        public static Map<Long, ExclusiveAffiliateItemInfo> getExclusiveAffiliateItems(){
                try{
                        CatalogClient client = new CatalogClient();
                        Long currentTime = new Date().getTime();
                        if(exclusiveAffiliateItems == null || fifteenMinsCounter < currentTime) {
                                exclusiveAffiliateItems = client.getClient().getExAffiliateItemInfo();
                                fifteenMinsCounter = new Date().getTime() + 15*60000;
                        }
                }catch(Exception ce){
                        logger.error("Unable to fetch exclusive items from catalog", ce);
                }
                return exclusiveAffiliateItems;
        }
        
        public static boolean validatePin(String pincode) {
                int pin;
                try {
                        pin = Integer.parseInt(pincode);
                }
                catch (NumberFormatException e) {
                        return false;
                }
                
                if (pin < 100000 || pin > 999999) {
                        return false;
                }
                return true;
        }
        
        public static boolean isValidEmail(String emailAddress) {
                
                if(emailAddress == null || emailAddress.isEmpty())      {
                        return false;
                }
                try {
                        InternetAddress address = new InternetAddress(emailAddress, true);
                        address.validate();
                        return true;
                        
                } catch (AddressException e) {
                        logger.error(emailAddress + " is not valid email address ", e);
                        return false;
                }
        }

        public static boolean validatePhone(String phone) {
                long iPhone;
                try {
                iPhone = Long.parseLong(phone);
                }
                catch (NumberFormatException e) {
                        return false;
                }
                
                if (iPhone < 1000000000l || iPhone > 9999999999l) {
                        return false;
                }
                return true;
        }
        
        public static String getItemIdStringInCart(Cart cart) {
            List<String> itemIds = new ArrayList<String>();
        for (Line line : cart.getLines()) {
            itemIds.add(Long.toString(line.getItemId()));
        }
        return StringUtils.join(itemIds, '_');
    }
        
        public static String fetchUrl(String url) throws Exception{
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet(url);
                HttpResponse response = client.execute(request);
                StringBuffer textView = new StringBuffer();

                // Get the response
                BufferedReader rd = new BufferedReader
                  (new InputStreamReader(response.getEntity().getContent()));
                    
                String line = "";
                while ((line = rd.readLine()) != null) {
                  textView.append(line);
                } 
                return textView.toString();
        }
        
        public static String getItemIdStringFromOrders(List<Order> orders) {
        List<String> itemIds = new ArrayList<String>();
        if (orders != null) {
            for (Order order : orders) {
                for (LineItem lItem : order.getLineitems()) {
                    itemIds.add(Long.toString(lItem.getItem_id()));
                }
            }
        }
        return StringUtils.join(itemIds, '_');
    }
        
        
        
        public static String getRechargeProviderName(long providerId) {
            return providersMap.get(providerId);
        }

    public static Map<Long, String> getMobileProvidersMap() {
        return mobileProvidersMap;
    }

    public static Map<Long, String> getDthProvidersMap() {
        return dthProvidersMap;
    }

    public static Map<Long, List<RechargePlan>> getOperatorPlanMap() {
        return operatorPlanMap;
    }
    
    public static Map<String, Map<String, String>> getUriOperatorMap(){
        return uriOperatorMap;
        }
    
    public static Map<String, String> getOperatorByUri(String uri){
        return uriOperatorMap.get(uri);
        }
    
    private final String USER_AGENT = "Mozilla/5.0";
    public final static String METHOD_POST = "POST";
    public final static String METHOD_GET = "GET";
    
    
    public String callRestApi(String apiUrl,String method,Map<String, String> paramsMap, Map<String, String> requestProperty){
        StringBuffer response = new StringBuffer();
        StringBuffer urlParameters= new StringBuffer("");
        try{

                        if (paramsMap != null) {
                                for (Entry<String, String> entry : paramsMap.entrySet()) {
                                        urlParameters.append(entry.getKey() + "=" + entry.getValue() + "&");
                                }
                        }
                        if (METHOD_GET.equalsIgnoreCase(method)) {
                                apiUrl += "?"+urlParameters.toString();
                        }
                        URL obj = new URL(apiUrl);
                        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                        if (apiUrl.startsWith("https")) {
                                con = (HttpsURLConnection) obj.openConnection();
                        }

                        // add reuqest header
                        con.setRequestMethod(method);
                        con.setRequestProperty("User-Agent", USER_AGENT);
                        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

                        if (requestProperty != null) {
                                for (Entry<String, String> entry : requestProperty.entrySet()) {
                                        con.setRequestProperty(entry.getKey(), entry.getValue());
                                }
                        }
                        // Send Post request
                        if (METHOD_POST.equalsIgnoreCase(method)) {
                                con.setDoOutput(true);
                                DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                                wr.writeBytes(urlParameters.toString());
                                wr.flush();
                                wr.close();
                        }

                        int responseCode = con.getResponseCode();
                        System.out.println("\nSending  request to URL : " + apiUrl);
                        System.out.println("Post parameters : " + urlParameters);
                        System.out.println("Response Code : " + responseCode);

                        if(responseCode==200){
                        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                        String inputLine;

                        while ((inputLine = in.readLine()) != null) {
                                response.append(inputLine);
                        }
                        in.close();
                        
                        }

                        // print result
                        System.out.println(response.toString());
                }catch(Exception e){
                
        }
        return response.toString();
    }
    
    public static void main(String args[]){

                //new Utils().callRestApi("https://graph.facebook.com/debug_token", Utils.METHOD_GET, paramsMap, null);
        }
}