Subversion Repositories SmartDukaan

Rev

Rev 1050 | Blame | Last modification | View Log | RSS feed

/**
 * 
 */
package in.shop2020.ui.util;

import in.shop2020.metamodel.core.Bullet;
import in.shop2020.metamodel.core.BulletDataObject;
import in.shop2020.metamodel.core.CompositeDataObject;
import in.shop2020.metamodel.core.Entity;
import in.shop2020.metamodel.core.EnumDataObject;
import in.shop2020.metamodel.core.Feature;
import in.shop2020.metamodel.core.FreeformContent;
import in.shop2020.metamodel.core.Media;
import in.shop2020.metamodel.core.PrimitiveDataObject;
import in.shop2020.metamodel.core.Slide;
import in.shop2020.metamodel.definitions.Catalog;
import in.shop2020.metamodel.definitions.DefinitionsContainer;
import in.shop2020.metamodel.definitions.EntityContainer;
import in.shop2020.metamodel.definitions.SlideDefinition;
import in.shop2020.metamodel.util.CreationUtils;
import in.shop2020.metamodel.util.ExpandedBullet;
import in.shop2020.metamodel.util.ExpandedCategory;
import in.shop2020.metamodel.util.ExpandedEntity;
import in.shop2020.metamodel.util.ExpandedFeature;
import in.shop2020.metamodel.util.ExpandedSlide;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.catalog.InventoryService.Client;
import in.shop2020.model.v1.catalog.Warehouse;
import in.shop2020.model.v1.catalog.status;
import in.shop2020.thrift.clients.CatalogServiceClient;
import in.shop2020.util.DBUtils;
import in.shop2020.util.Utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

/**
 * Driver class to merge Java data objects with VTL script
 * 
 * @author naveen
 *
 */
public class VUI {

        /**
         * Usage: VUI [entity|category|category_carousal|diff|entitysummary|entityhomesnippet|entitywidgetsnippet] [Entity ID|Category ID|EntityID1_EntityID2] {Template file name}
         * 
         * @param args
         */
        public static void main(String[] args) throws Exception {
                //diffAll();
                //System.exit(0);
                
                String[] commands = new String[] {"entity", "category", "category_carousal", "diff", "entities"};
                String[] datatypes = new String[] {"Entity ID", "Category ID", "EntityID1_EntityID2"};

                String usage = "Usage: VUI ["+ StringUtils.join(commands, "|") +"] ["+ 
                        StringUtils.join(datatypes, "|") + "] ";
                
                if(args.length < 1) {
                        System.out.println(usage);
                        System.exit(-1);
                }
                String inputCommand = args[0];
                String inputID = null;
                if(args.length == 2){
                        inputID = args[1];
                }
                //String templateFilename = args[2];
                
                
                long catalogId = 0;
                if(inputCommand.equals("entity") || inputCommand.equals("category") ||  inputCommand.equals("category_carousal")) {
                        try {
                                catalogId = Long.parseLong(inputID);
                        }
                        catch (NumberFormatException nfe) {
                                System.out.println("Invalid ID - " + inputID);
                                System.exit(-1);
                        }
                }
                
                // Setup
                Velocity.init("src/in/shop2020/ui/util/velocity.properties");
                VelocityContext context = new VelocityContext();

                String templateFile = null;
                
                Template template = null;
                String exportFileName = null;
                
                DefinitionsContainer defs = 
                        Catalog.getInstance().getDefinitionsContainer();
                
                EntityContainer ents = 
                        Catalog.getInstance().getEntityContainer();

                
                // Entities
                if(inputCommand.equals("entity")) {
                        File exportFile = new File(Utils.EXPORT_ENTITIES_PATH + catalogId);
                        if(!exportFile.exists()) {
                                exportFile.mkdir();
                        }
                        /*
                        templateFile= Utils.VTL_SRC_PATH + "product_summary.vm";
                        getProductSummaryHtml(catalogId, templateFile);
                        templateFile= Utils.VTL_SRC_PATH + "entity_snippet_for_widget.vm";
                        getEntitySnippetHtml(catalogId, templateFile);
                        templateFile= Utils.VTL_SRC_PATH + "entity_snippet_for_homepage.vm";
                        getEntityHomeSnippetHtml(catalogId, templateFile);
                        templateFile= Utils.VTL_SRC_PATH + "entity_snippet_for_searchpage.vm";
                        getEntitySearchSnippetHtml(catalogId, templateFile);
                        templateFile= Utils.VTL_SRC_PATH + "slideguide_img_video.vm";
                        getEntitySlideGuideHtml(catalogId, templateFile);
                        */
                }else 
                
                        if(inputCommand.equals("entities")){
                        CatalogServiceClient catalogServiceClient = new CatalogServiceClient();
                        Client client = catalogServiceClient.getClient();
                        
                        
                        List<Item> items = client.getAllItemsByStatus(status.ACTIVE);
                        Date todate = new Date();
                        
                        for(Item item: items){
                                if(todate.getTime() < item.getStartDate()){
                                        continue;
                                }
                                long itemId = item.getId();
                                catalogId = item.getCatalogItemId();
                                File exportFile = new File(Utils.EXPORT_ENTITIES_PATH + catalogId);
                                if(!exportFile.exists()) {
                                        exportFile.mkdir();
                                }
                                templateFile= Utils.VTL_SRC_PATH + "product_summary.vm";
                                getProductSummaryHtml(catalogId, itemId, templateFile);
                                templateFile= Utils.VTL_SRC_PATH + "entity_snippet_for_widget.vm";
                                getEntitySnippetHtml(catalogId, itemId, templateFile);
                                templateFile= Utils.VTL_SRC_PATH + "entity_snippet_for_homepage.vm";
                                getEntityHomeSnippetHtml(catalogId, itemId, templateFile);
                                templateFile= Utils.VTL_SRC_PATH + "entity_snippet_for_searchpage.vm";
                                getEntitySearchSnippetHtml(catalogId, itemId, templateFile);
                                templateFile= Utils.VTL_SRC_PATH + "entity_snippet_for_categorypage.vm";
                                getEntityCategorySnippetHtml(catalogId, itemId, templateFile);
                                templateFile= Utils.VTL_SRC_PATH + "slideguide_img_video.vm";
                                getEntitySlideGuideHtml(catalogId, itemId, templateFile);
                                getEntityTitleSnippetHtml(catalogId);
                                getEntityMetaDescriptionSnippetHtml(catalogId);
                                getEntityMetaKeywordSnippetHtml(catalogId);
                        }
                        
                }
                
                // Category definitions
                else if(inputCommand.equals("category")) {                      
                        ExpandedCategory expCategory = defs.getExpandedCategory(catalogId);
                        Utils.info("expCategory=" + expCategory);
                        
                        context.put("expcategory", expCategory);
                        template = Velocity.getTemplate(templateFile);
                        
                        exportFileName = Utils.EXPORT_DEFINITIONS_PATH + catalogId + ".html";
                }

                // Category carousal
                else if(inputCommand.equals("category_carousal")) {
                        String categoryName = defs.getCategory(catalogId).getLabel();
                        
                        //FIXME get category wise entities
                        Collection<Entity> entities = CreationUtils.getEntities(catalogId);
                        
                        
                        List<String[]> entitiesToShow = new ArrayList<String[]>();
                        
                        for(Entity entity : entities) {
                                String snippets[] = new String[4];
                                
                                // Entity ID
                                snippets[0] = new Long(entity.getID()).toString();
                                
                                Feature feature = ents.getFeature(entity.getID(), 
                                                Utils.SNIPPETS_FEATURE_DEFINITIONID);
                                
                                List<Bullet> bullets = feature.getBullets();
                                
                                if(bullets.size() > 0) {
                                        snippets[1] = ((PrimitiveDataObject)bullets.get(0).
                                                        getDataObject()).getValue();
                                }
                                
                                if(bullets.size() > 1) {
                                        snippets[2] = ((PrimitiveDataObject)bullets.get(1).
                                                        getDataObject()).getValue();
                                }
                                
                                if(bullets.size() > 2) {
                                        snippets[3] = ((PrimitiveDataObject)bullets.get(2).
                                                        getDataObject()).getValue();
                                }

                                Utils.info("snippets=" + Arrays.toString(snippets));
                                entitiesToShow.add(snippets);
                        }
                        
                        Utils.info("categoryName=" + categoryName);
                        Utils.info("entitiesToShow=" + entitiesToShow);
                        
                        context.put("categoryName", categoryName);
                        context.put("entitiesToShow", entitiesToShow);
                        
                        template = Velocity.getTemplate(templateFile);
                        exportFileName = Utils.EXPORT_CATEGORY_HOMES_PATH + catalogId + ".html";
                        Utils.info("Export File Names " + exportFileName );
                }

                // Difference
                else if(inputCommand.equals("diff")) {
                        String[] entityIDs = StringUtils.split(inputID, "_");
                        if(entityIDs.length < 2) {
                                System.out.println("Invalid IDs - " + inputID);
                                System.exit(-1);
                        }
                        
                        long entityID1 = 0L;
                        long entityID2 = 0L;
                        try {
                                entityID1 = Long.parseLong(entityIDs[0]);
                                entityID2 = Long.parseLong(entityIDs[1]);
                        } catch(NumberFormatException nfe) {
                                System.out.println("Invalid IDs - " + inputID);
                                System.exit(-1);
                        }
                        
                        Utils.info("entityIDs=" + Arrays.toString(entityIDs));
                        
                        ExpandedEntity expEntity1 = ents.getExpandedEntity(entityID1);
                        ExpandedEntity expEntity2 = ents.getExpandedEntity(entityID2);
                        
                        List<ExpandedSlide[]> mergedSlides = 
                                getMergedSlides(expEntity1, expEntity2);
                        Utils.info("mergedSlides=" + mergedSlides);
                        
                        Collection<String[]> mergedComparisonScores = 
                                getMergedComparisonScores(expEntity1, expEntity2);
                        Utils.info("mergedComparisonScores=" + mergedComparisonScores);

                        int scoreEntity1 = CreationUtils.getEntityComparisonScores(expEntity1.getID());
                        int scoreEntity2 = CreationUtils.getEntityComparisonScores(expEntity2.getID());
                        

                        context.put("expEntity1", expEntity1);
                        context.put("expEntity2", expEntity2);
                        context.put("mergedSlides", mergedSlides);
                        context.put("mergedComparisonScores", mergedComparisonScores);
                        context.put("scoreEntity1", scoreEntity1);
                        context.put("scoreEntity2", scoreEntity2);
                        
                        template = Velocity.getTemplate(templateFile);
                        exportFileName = Utils.EXPORT_DIFF_PATH + entityIDs[0] + "_" +
                                entityIDs[1] + ".html";
                }
                
                if(template != null) { 
                        File exportFile = new File(exportFileName);
                        if(!exportFile.exists()) {
                                exportFile.createNewFile();
                        }
                        
                        BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(exportFile)));
                        
                        template.merge(context, writer);
                        
                        writer.flush();
                        writer.close();
                        Utils.info("Export Complete!");
                }
        }



        private static void getEntityMetaDescriptionSnippetHtml(long catalogId) {
        EntityContainer entContainer =  Catalog.getInstance().getEntityContainer();
                
                ExpandedEntity expEntity;
                try {
                        expEntity = entContainer.getExpandedEntity(catalogId);
                        String description = "Best Price " + expEntity.getBrand() + " " + expEntity.getModelName() 
                                + " " + expEntity.getModelNumber() + " ";
                        
                        if(expEntity.getCategory().getParentCategory().getID() == 10011) {
                                description += expEntity.getCategory().getLabel() + " in India.";
                        }
                        else {
                                description += ".";
                        }
                        description += " Experience n' buy online. FREE Next Day delivery."
                                + " Original product - Full manufacturer warranty. Comprehensive reviews.";
                        
                        description = description.replaceAll("--", "-");
                        String exportFileName = Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator + "MetaDescriptionSnippet.html";
                        File exportFile = new File(exportFileName);
                        if(!exportFile.exists()) {
                                exportFile.createNewFile();
                        }
                        
                        BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(exportFile)));

                        writer.write(description);
                        
                        writer.flush();
                        writer.close();
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }

        private static void getEntityMetaKeywordSnippetHtml(long catalogId) {
        EntityContainer entContainer =  Catalog.getInstance().getEntityContainer();
                
                ExpandedEntity expEntity;
                try {
                        expEntity = entContainer.getExpandedEntity(catalogId);
                        String keywords = expEntity.getBrand() + " " + expEntity.getModelName() + " " + expEntity.getModelNumber() + ", ";
                        if(expEntity.getCategory().getParentCategory().getID() == 10001) {
                                keywords += expEntity.getBrand() + " mobile phones, ";
                        }
                        if(expEntity.getCategory().getParentCategory().getID() == 10011) {
                                keywords += "phone accessories, ";
                        }
                        keywords += expEntity.getBrand() + " " + expEntity.getModelName() + " " + expEntity.getModelNumber() + " Price, ";
                        keywords += expEntity.getBrand() + " " + expEntity.getModelName() + " " + expEntity.getModelNumber() + " India, ";
                        if(expEntity.getCategory().getParentCategory().getID() == 10001) {
                        keywords += expEntity.getBrand() + " " + expEntity.getModelName() + " " + expEntity.getModelNumber() + " Review, ";
                        }
                        
                        String exportFileName = Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator + "MetaKeywordsSnippet.html";
                        File exportFile = new File(exportFileName);
                        if(!exportFile.exists()) {
                                exportFile.createNewFile();
                        }
                        
                        BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(exportFile)));

                        writer.write(keywords);
                        
                        writer.flush();
                        writer.close();
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }

        private static void getEntitySlideGuideHtml(long catalogId,  long itemId, String templateFile) throws Exception {
                EntityContainer entContainer = 
                        Catalog.getInstance().getEntityContainer();

                ExpandedEntity expEntity = entContainer.getExpandedEntity(catalogId);
                Utils.logger.info("expEntity=" + expEntity);
                
                Map<String, Media> media= null;
                
                //Map<String, Media> media = CreationUtils.getRawMedia(catalogId);

                VelocityContext context = new VelocityContext();

                context.put("expentity", expEntity);
                context.put("media", media);
                String exportFileName = null;

                Template template = Velocity.getTemplate(templateFile);
                exportFileName = Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator + "SlideGuide.html";

                File exportFile = new File(exportFileName);
                if(!exportFile.exists()) {
                        exportFile.createNewFile();
                }
                
                BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(exportFile)));
                
                //Template template = Velocity.getTemplate(templateFile);
                template.merge(context, writer);
                
                writer.flush();
                writer.close();
                Utils.info("Export Complete!");

        }


        
        /**
         * 
         * @param expEntity1
         * @param expEntity2
         * @return
         * @throws Exception 
         */
        private static Collection<String[]> getMergedComparisonScores(
                        ExpandedEntity expEntity1, ExpandedEntity expEntity2) 
                        throws Exception {
                EntityContainer ents = Catalog.getInstance().getEntityContainer();
                DefinitionsContainer defs = 
                        Catalog.getInstance().getDefinitionsContainer();
                
                Map<String, String[]> mergedSlideScores = 
                        new LinkedHashMap<String, String[]>();
                
                Map<Long, Integer> cmpSlideScores1 = CreationUtils.getSlideComparisonScores(expEntity1.getID());
                
                for(Long slideID : cmpSlideScores1.keySet()) {
                        SlideDefinition slideDef = defs.getSlideDefinition(
                                        slideID.longValue());
                        
                        String slideLabel = slideDef.getLabel();
                        String[] details = new String[3];
                        
                        details[0] = slideLabel;
                        
                        Integer score = cmpSlideScores1.get(slideID);
                        if(score != null) {
                                details[1] = score.toString();
                        }
                        else {
                                details[1] = "-1";
                        }
                        
                        // To be determined in loop over 2nd entity's scores
                        details[2] = "-1";
                        
                        mergedSlideScores.put(slideLabel, details);
                }

                Map<Long, Integer> cmpSlideScores2 = CreationUtils.getSlideComparisonScores(expEntity2.getID());

                for(Long slideID : cmpSlideScores2.keySet()) {
                        SlideDefinition slideDef = defs.getSlideDefinition(
                                        slideID.longValue());
                        
                        String slideLabel = slideDef.getLabel();

                        String[] details = null;
                        if(mergedSlideScores.containsKey(slideLabel)) {
                                details = mergedSlideScores.get(slideLabel);
                        }
                        else {
                                details = new String[3];
                                
                                details[0] = slideLabel;
                                details[1] = "-1";
                                
                                mergedSlideScores.put(slideLabel, details);
                        }

                        Integer score = cmpSlideScores2.get(slideID);
                        if(score != null) {
                                details[2] = score.toString();
                        }
                        else {
                                details[2] = "-1";
                        }
                }
                
                return mergedSlideScores.values();
        }

        /**
         * 
         * @param expEntity1
         * @param expEntity2
         */
        private static List<ExpandedSlide[]> getMergedSlides(
                        ExpandedEntity expEntity1, ExpandedEntity expEntity2) {
                List<ExpandedSlide[]> mergedSlides = new ArrayList<ExpandedSlide[]>();
                
                EntityContainer ents = Catalog.getInstance().getEntityContainer();
                
                List<ExpandedSlide> expSlidesEntity1 = expEntity1.getExpandedSlides();
                
                for(ExpandedSlide expSlide1 : expSlidesEntity1) {
                        String slideLabel = expSlide1.getSlideDefinition().getLabel();
                        
                        ExpandedSlide expSlide2 = ents.getParentExpandedSlide(
                                        expEntity2, slideLabel);
                        
                        if(expSlide2 != null) {
                                ExpandedSlide[] comparisonSlides = new ExpandedSlide[2];
                                comparisonSlides[0] = expSlide1;
                                comparisonSlides[1] = expSlide2;
                                        
                                mergedSlides.add(comparisonSlides);
                        }
                }
                
                return mergedSlides;
        }
        
        public static void diffAll() throws Exception {
                long[] entityIDs = new long[] {
                                1000001,
                                1000002,
                                1000003,
                                1000004,
                                1000005,
                                1000006,
                                1000007,
                                1000008,
                                1000009,
                                1000010,
                                1000011,
                                1000012,
                                1000013,
                                1000014,
                                1000015
                };
                
                for(int i=0;i<entityIDs.length;i++) {
                        for(int j=0;j<entityIDs.length;j++) {
                                diff(entityIDs[i], entityIDs[j]);
                        }
                }
        }
        
        public static void diff(long entityID1, long entityID2) throws Exception {
                // Setup
                Velocity.init("src/in/shop2020/ui/util/velocity.properties");
                VelocityContext context = new VelocityContext();

                String templateFile = Utils.VTL_SRC_PATH + "jquery_diff_slideguide.vm";
                
                Template template = null;
                String exportFileName = null;
                
                EntityContainer ents = Catalog.getInstance().getEntityContainer();
                
                ExpandedEntity expEntity1 = ents.getExpandedEntity(entityID1);
                ExpandedEntity expEntity2 = ents.getExpandedEntity(entityID2);
                
                List<ExpandedSlide[]> mergedSlides = 
                        getMergedSlides(expEntity1, expEntity2);
                Utils.info("mergedSlides=" + mergedSlides);
                
                Collection<String[]> mergedComparisonScores = 
                        getMergedComparisonScores(expEntity1, expEntity2);
                Utils.info("mergedComparisonScores=" + mergedComparisonScores);
        
                int scoreEntity1 = CreationUtils.getEntityComparisonScores(expEntity1.getID());
        
                int scoreEntity2 = CreationUtils.getEntityComparisonScores(expEntity2.getID());
        
                context.put("expEntity1", expEntity1);
                context.put("expEntity2", expEntity2);
                context.put("mergedSlides", mergedSlides);
                context.put("mergedComparisonScores", mergedComparisonScores);
                context.put("scoreEntity1", scoreEntity1);
                context.put("scoreEntity2", scoreEntity2);
                
                template = Velocity.getTemplate(templateFile);
                exportFileName = Utils.EXPORT_DIFF_PATH + entityID1 + "_" + entityID2 + 
                        ".html";

                File exportFile = new File(exportFileName);
                if(!exportFile.exists()) {
                        exportFile.createNewFile();
                }
                
                BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(exportFile)));
                
                template.merge(context, writer);
                
                writer.flush();
                writer.close();
                Utils.info("Export Complete!");
        }
        
        public static void getProductSummaryHtml(long catalogId,  long itemId, String templateFile) {
                CatalogServiceClient catalogServiceClient = null;
                Client client = null;
                String htmlString = "";

                try {
                        double rating_all  = 0.0;
                        catalogServiceClient = new CatalogServiceClient();
                        client = catalogServiceClient.getClient();
                        List<Item> items = client.getItemsByCatalogId(catalogId);
                        

                        List<Map<String, String>> itemDetails = new ArrayList<Map<String,String>>(); 
                        Date todate = new Date();
                        
                        for(Item item: items){
                                if(item.getItemStatus() != status.ACTIVE || todate.getTime() < item.getStartDate()){
                                        continue;
                                }
                                Map<String, String> itemDetail = new HashMap<String, String>();
                                double sellingPrice = item.getSellingPrice();
                                double mrp = item.getMrp();
                                double saving = Math.round((mrp-sellingPrice)/mrp*100);
                                itemDetail.put("ITEM_ID", ((int)item.getId())+"");
                                itemDetail.put("CATALOG_ID", ((int)item.getCatalogItemId())+"");
                                itemDetail.put("SP", ((int)item.getSellingPrice())+"");
                                itemDetail.put("MRP", ((int)item.getMrp())+"");
                                itemDetail.put("SAVING", ((int)saving)+"");
                                itemDetail.put("COLOR", item.getColor());
                                itemDetails.add(itemDetail);
                        }
                        
                        // For an entity
                        EntityContainer entContainer =  Catalog.getInstance().getEntityContainer();
                        ExpandedEntity expEntity = entContainer.getExpandedEntity(catalogId);
                        
                        String title = expEntity.getBrand() + " " + expEntity.getModelName() + " " + expEntity.getModelNumber();
                        String categoryName = expEntity.getCategory().getLabel();
                        String tagline = "";
                        String warranty = "";
                        List<Feature>  features = expEntity.getSlide(130054).getFeatures();
                        for(Feature feature: features){
                                if(feature.getFeatureDefinitionID() == 120084){
                                        PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
                                        tagline = dataObject.getValue(); 
                                }
                                if(feature.getFeatureDefinitionID() == 120125){
                                        ExpandedFeature expFeature = new ExpandedFeature(feature);
                                        ExpandedBullet expBullet =expFeature.getExpandedBullets().get(0);
                                        if(expBullet != null){
                                                warranty = expBullet.getValue() + " "+ expBullet.getUnit().getShortForm();
                                        }
                                }
                        }
                        
                        
                        
                        
                        long categoryId = expEntity.getCategory().getID();
                        Map<String,String> params = new HashMap<String, String>();
                        params.put("TITLE", title);
                        params.put("CATEGORY_ID", ((int)categoryId)+"");
                        params.put("CATEGORY_NAME", categoryName);
                        params.put("CATEGORY_URL", categoryName.replaceAll(" ", "-").toLowerCase() + "/" + categoryId);
                        /*
                        params.put("SELLING_PRICE", ((int)sellingPrice)+"");
                        params.put("MRP", ((int)mrp)+"");
                        params.put("SAVING", ((int)saving)+"");
                        params.put("ITEM_ID", ((int)itemId)+"");
                        */
                        
                        
                        params.put("RATING_ALL", ((int)rating_all)+"");
                        params.put("CATALOG_ID", ((int)catalogId)+"");
                        params.put("TAGLINE", tagline);
                        params.put("WARRANTY", warranty);
                        
                        VelocityContext context = new VelocityContext();
                        
                        context.put("itemDetails", itemDetails);
                        
                        context.put("params", params);
                        
                        String exportFileName = Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator + "ProductDetail.html";
        
                        File exportFile = new File(exportFileName);
                        if(!exportFile.exists()) {
                                exportFile.createNewFile();
                        }
                        
                        BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(exportFile)));
                        
                        Template template = Velocity.getTemplate(templateFile);
                        template.merge(context, writer);
                        
                        writer.flush();
                        writer.close();
                        Utils.info("Export Complete!");

                        
                } catch (Exception e) {
                        e.printStackTrace();
                }
        
                //return htmlString;
        }

        private static void getEntitySnippetHtml(long catalogId,  long itemId, String templateFile) {
                CatalogServiceClient catalogServiceClient = null;
                Client client = null;

                
                EntityContainer entContainer =  Catalog.getInstance().getEntityContainer();
                ExpandedEntity expEntity;
                try {
                        
                        expEntity = entContainer.getExpandedEntity(catalogId);
                        String title = expEntity.getBrand() + " " + expEntity.getModelName() + " " + expEntity.getModelNumber();
                        String url = "/" + expEntity.getCategory().getParentCategory().getLabel().toLowerCase().replace(' ', '-') + "/" 
                            + expEntity.getBrand().toLowerCase().replace(' ', '-')
                    + "-" + expEntity.getModelName().toLowerCase().replace(' ', '-') 
                            + "-" + expEntity.getModelNumber().toLowerCase().replace(' ', '-')
                        + "-" + catalogId;
                        url = url.replaceAll("--", "-");
                        
                        String tinySnippet = "";
                        List<Feature>  features = expEntity.getSlide(130054).getFeatures();
                        for(Feature feature: features){
                                if(feature.getFeatureDefinitionID() == 120089){
                                        PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
                                        tinySnippet = dataObject.getValue(); 
                                }
                        }

                        catalogServiceClient = new CatalogServiceClient();
                        client = catalogServiceClient.getClient();
                        
                        List<Item> items = client.getItemsByCatalogId(catalogId);
                        List<Map<String, String>> itemDetails = new ArrayList<Map<String,String>>(); 
                        
                        Item minPriceItem = null; 
                        for(Item item: items){
                                Map<String, String> itemDetail = new HashMap<String, String>();
                                if(minPriceItem == null || minPriceItem.getSellingPrice() > item.getSellingPrice()){
                                        minPriceItem = item;
                                }
                                double sellingPrice = item.getSellingPrice();
                                double mrp = item.getMrp();
                                double saving = Math.round((mrp-sellingPrice)/mrp*100);
                                itemDetail.put("ITEM_ID", ((int)item.getId())+"");      
                                itemDetail.put("SP", ((int)item.getSellingPrice())+"");
                                itemDetail.put("MRP", ((int)item.getMrp())+"");
                                itemDetail.put("SAVING", ((int)saving)+"");
                                itemDetail.put("COLOR", item.getColor());
                                itemDetails.add(itemDetail);
                        }
                        
                        Map<String,String> params = new HashMap<String, String>();
                        params.put("TITLE", title);
                        params.put("URL", url);
                        params.put("SELLING_PRICE", ((int)minPriceItem.getSellingPrice())+"");
                        params.put("MRP", ((int)minPriceItem.getMrp())+"");
                        params.put("CATALOG_ID", ((int)catalogId)+"");
                        params.put("ITEM_ID", minPriceItem.getId()+"");
                        params.put("TINY_SNIPPET", tinySnippet);
                        
                        VelocityContext context = new VelocityContext();
                        context.put("itemDetails", itemDetails);
                        context.put("params", params);

                        String exportFileName = Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator + "WidgetSnippet.html";
                        File exportFile = new File(exportFileName);
                        if(!exportFile.exists()) {
                                exportFile.createNewFile();
                        }
                        
                        BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(exportFile)));
                        
                        Template template = Velocity.getTemplate(templateFile);
                        template.merge(context, writer);
                        
                        writer.flush();
                        writer.close();
                        Utils.info("Export Complete!");

                        
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
        private static void getEntityHomeSnippetHtml(long catalogId,  long itemId, String templateFile) {
                EntityContainer entContainer =  Catalog.getInstance().getEntityContainer();
                Map<String,String> params = new HashMap<String, String>();
                CatalogServiceClient catalogServiceClient = null;
                Client client = null;
                
                ExpandedEntity expEntity;
                try {
                        expEntity = entContainer.getExpandedEntity(catalogId);
                        String title = expEntity.getBrand() + " " + expEntity.getModelName()+ " " + expEntity.getModelNumber();
                        String url = "/" + expEntity.getCategory().getParentCategory().getLabel().toLowerCase().replace(' ', '-') + "/"
                            + expEntity.getBrand().toLowerCase().replace(' ', '-')
                        + "-" + expEntity.getModelName().toLowerCase().replace(' ', '-') 
                        + "-" + expEntity.getModelNumber().toLowerCase().replace(' ', '-')
                    + "-" + catalogId;
                        url = url.replaceAll("--", "-");
                        catalogServiceClient = new CatalogServiceClient();
                        client = catalogServiceClient.getClient();

                        String tinySnippet = "";
                        List<Feature>  features = expEntity.getSlide(130054).getFeatures();
                        for(Feature feature: features){
                                if(feature.getFeatureDefinitionID() == 120081){
                                        List<Bullet> bullets = feature.getBullets();
                                        int count = 1;
                                        for(Bullet bullet: bullets){
                                                PrimitiveDataObject dataObject = (PrimitiveDataObject)bullet.getDataObject();
                                                tinySnippet = dataObject.getValue();
                                                params.put("SNIPPET_"+count++, tinySnippet);
                                                System.out.println("Tiny Snippets is " + dataObject.getValue());
                                        }
                                }
                        }


                        
                        List<Item> items = client.getItemsByCatalogId(catalogId);
                        List<Map<String, String>> itemDetails = new ArrayList<Map<String,String>>(); 
                        
                        Item minPriceItem = null;
                        Date todate = new Date();
                        
                        for(Item item: items){
                                if(item.getItemStatus() != status.ACTIVE || todate.getTime() < item.getStartDate()){
                                        continue;
                                }
                                Map<String, String> itemDetail = new HashMap<String, String>();
                                if(minPriceItem == null || minPriceItem.getSellingPrice() > item.getSellingPrice()){
                                        minPriceItem = item;
                                }
                                double sellingPrice = item.getSellingPrice();
                                double mrp = item.getMrp();
                                double saving = Math.round((mrp-sellingPrice)/mrp*100);
                                itemDetail.put("ITEM_ID", ((int)item.getId())+"");      
                                itemDetail.put("SP", ((int)item.getSellingPrice())+"");
                                itemDetail.put("MRP", ((int)item.getMrp())+"");
                                itemDetail.put("SAVING", ((int)saving)+"");
                                itemDetail.put("COLOR", item.getColor());
                                itemDetails.add(itemDetail);
                        }
                                
                        params.put("TITLE", title);
                        params.put("URL", url);
                        params.put("SELLING_PRICE", ((int)minPriceItem.getSellingPrice())+"");
                        params.put("MRP", ((int)minPriceItem.getMrp())+"");
                        params.put("CATALOG_ID", ((int)catalogId)+"");
                        params.put("ITEM_ID", minPriceItem.getId()+"");
                        
                        VelocityContext context = new VelocityContext();
                        context.put("itemDetails", itemDetails);
                        context.put("params", params);
                        //htmlString = getHtmlFromVelocity(templateFile, context);
                        
                        String exportFileName = Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator + "HomeSnippet.html";
                        File exportFile = new File(exportFileName);
                        if(!exportFile.exists()) {
                                exportFile.createNewFile();
                        }
                        
                        BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(exportFile)));
                        
                        Template template = Velocity.getTemplate(templateFile);
                        template.merge(context, writer);
                        
                        writer.flush();
                        writer.close();
                        Utils.info("Export Complete!");

                        
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
        
        private static void getEntityCategorySnippetHtml(long catalogId,  long itemId, String templateFile) {
                EntityContainer entContainer =  Catalog.getInstance().getEntityContainer();
                Map<String,String> params = new HashMap<String, String>();
                CatalogServiceClient catalogServiceClient = null;
                Client client = null;
                                
                
                ExpandedEntity expEntity;
                try {
                        expEntity = entContainer.getExpandedEntity(catalogId);
                        String title = expEntity.getBrand() + " " + expEntity.getModelName()+ " " + expEntity.getModelNumber();
                        catalogServiceClient = new CatalogServiceClient();
                        client = catalogServiceClient.getClient();
                        String url = "/" + expEntity.getCategory().getParentCategory().getLabel().toLowerCase().replace(' ', '-') + "/" 
                            + expEntity.getBrand().toLowerCase().replace(' ', '-')
                + "-" + expEntity.getModelName().toLowerCase().replace(' ', '-') 
                        + "-" + expEntity.getModelNumber().toLowerCase().replace(' ', '-')
                    + "-" + catalogId;
                        url = url.replaceAll("--", "-");
                        String tinySnippet = "";
                        List<Feature>  features = expEntity.getSlide(130054).getFeatures();
                        for(Feature feature: features){
                                if(feature.getFeatureDefinitionID() == 120081){
                                        List<Bullet> bullets = feature.getBullets();
                                        int count = 1;
                                        for(Bullet bullet: bullets){
                                                PrimitiveDataObject dataObject = (PrimitiveDataObject)bullet.getDataObject();
                                                tinySnippet = dataObject.getValue();
                                                params.put("SNIPPET_"+count++, tinySnippet);
                                                System.out.println("Tiny Snippets is " + dataObject.getValue());
                                        }
                                }
                        }


                        List<Item> items = client.getItemsByCatalogId(catalogId);
                        List<Map<String, String>> itemDetails = new ArrayList<Map<String,String>>(); 
                        
                        
                        Item minPriceItem = null;
                        Date todate = new Date();
                        for(Item item: items){
                                if(item.getItemStatus() != status.ACTIVE || todate.getTime() < item.getStartDate()){
                                        continue;
                                }
                                Map<String, String> itemDetail = new HashMap<String, String>();
                                if(minPriceItem == null || minPriceItem.getSellingPrice() > item.getSellingPrice()){
                                        minPriceItem = item;
                                }
                                double sellingPrice = item.getSellingPrice();
                                double mrp = item.getMrp();
                                double saving = Math.round((mrp-sellingPrice)/mrp*100);
                                itemDetail.put("ITEM_ID", ((int)item.getId())+"");      
                                itemDetail.put("SP", ((int)item.getSellingPrice())+"");
                                itemDetail.put("MRP", ((int)item.getMrp())+"");
                                itemDetail.put("SAVING", ((int)saving)+"");
                                itemDetail.put("COLOR", item.getColor());
                                itemDetails.add(itemDetail);
                        }
                                
                        params.put("TITLE", title);
                        params.put("URL", url);
                        params.put("SELLING_PRICE", ((int)minPriceItem.getSellingPrice())+"");
                        params.put("MRP", ((int)minPriceItem.getMrp())+"");
                        params.put("CATALOG_ID", ((int)catalogId)+"");
                        params.put("ITEM_ID", minPriceItem.getId()+"");
                        
                        VelocityContext context = new VelocityContext();
                        context.put("itemDetails", itemDetails);
                        context.put("params", params);
                        //htmlString = getHtmlFromVelocity(templateFile, context);
                        
                        String exportFileName = Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator + "CategorySnippet.html";
                        File exportFile = new File(exportFileName);
                        if(!exportFile.exists()) {
                                exportFile.createNewFile();
                        }
                        
                        BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(exportFile)));
                        
                        Template template = Velocity.getTemplate(templateFile);
                        template.merge(context, writer);
                        
                        writer.flush();
                        writer.close();
                        Utils.info("Export Complete!");

                        
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }

        private static void getEntityTitleSnippetHtml(long catalogId) {
                EntityContainer entContainer =  Catalog.getInstance().getEntityContainer();
                
                ExpandedEntity expEntity;
                try {
                        expEntity = entContainer.getExpandedEntity(catalogId);
                        String title = expEntity.getBrand() + " " + expEntity.getModelName()+ " " 
                    + expEntity.getModelNumber();
                        if(expEntity.getCategory().getParentCategory().getID() == 10001) {
                                title +=  " | " + expEntity.getBrand() + " Mobile Phones";
                        }
                        if(expEntity.getCategory().getParentCategory().getID() == 10011) {
                                title += " " + expEntity.getCategory().getLabel()
                            + " | " + expEntity.getBrand() + " Mobile Phone Accessories";
                        }
                        title += " | Saholic.com";
                        
                        String exportFileName = Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator + "TitleSnippet.html";
                        File exportFile = new File(exportFileName);
                        if(!exportFile.exists()) {
                                exportFile.createNewFile();
                        }
                        
                        BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(exportFile)));

                        writer.write(title);
                        
                        writer.flush();
                        writer.close();
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }

        
        private static void getEntitySearchSnippetHtml(long catalogId,  long itemId, String templateFile) {
                EntityContainer entContainer =  Catalog.getInstance().getEntityContainer();
                Map<String,String> params = new HashMap<String, String>();
                CatalogServiceClient catalogServiceClient = null;
                Client client = null;
                
                
                
                ExpandedEntity expEntity;
                try {
                        expEntity = entContainer.getExpandedEntity(catalogId);
                        String title = expEntity.getBrand() + " " + expEntity.getModelName()+ " " + expEntity.getModelNumber();
                        String url = "/" + expEntity.getCategory().getParentCategory().getLabel().toLowerCase().replace(' ', '-') + "/" 
                            + expEntity.getBrand().toLowerCase().replace(' ', '-')
                + "-" + expEntity.getModelName().toLowerCase().replace(' ', '-') 
                        + "-" + expEntity.getModelNumber().toLowerCase().replace(' ', '-')
                    + "-" + catalogId;
                        url = url.replaceAll("--", "-");
                        catalogServiceClient = new CatalogServiceClient();
                        client = catalogServiceClient.getClient();
                        //Item item = client.getItem(itemId);
                        String tinySnippet = "";
                        List<Feature>  features = expEntity.getSlide(130054).getFeatures();
                        for(Feature feature: features){
                                if(feature.getFeatureDefinitionID() == 120081){
                                        List<Bullet> bullets = feature.getBullets();
                                        int count = 1;
                                        for(Bullet bullet: bullets){
                                                PrimitiveDataObject dataObject = (PrimitiveDataObject)bullet.getDataObject();
                                                tinySnippet = dataObject.getValue();
                                                params.put("SNIPPET_"+count++, tinySnippet);
                                                System.out.println("Tiny Snippets is " + dataObject.getValue());
                                        }
                                }
                        }


                        List<Item> items = client.getItemsByCatalogId(catalogId);
                        List<Map<String, String>> itemDetails = new ArrayList<Map<String,String>>(); 
                        
                        Item minPriceItem = null;
                        Date todate = new Date();
                        for(Item item: items){
                                if(item.getItemStatus() != status.ACTIVE || todate.getTime() < item.getStartDate()){
                                        continue;
                                }
                                Map<String, String> itemDetail = new HashMap<String, String>();
                                if(minPriceItem == null || minPriceItem.getSellingPrice() > item.getSellingPrice()){
                                        minPriceItem = item;
                                }
                                double sellingPrice = item.getSellingPrice();
                                double mrp = item.getMrp();
                                double saving = Math.round((mrp-sellingPrice)/mrp*100);
                                itemDetail.put("ITEM_ID", ((int)item.getId())+"");      
                                itemDetail.put("SP", ((int)item.getSellingPrice())+"");
                                itemDetail.put("MRP", ((int)item.getMrp())+"");
                                itemDetail.put("SAVING", ((int)saving)+"");
                                itemDetail.put("COLOR", item.getColor());
                                itemDetails.add(itemDetail);
                        }
                                
                        params.put("TITLE", title);
                        params.put("URL", url);
                        params.put("SELLING_PRICE", ((int)minPriceItem.getSellingPrice())+"");
                        params.put("MRP", ((int)minPriceItem.getMrp())+"");
                        params.put("CATALOG_ID", ((int)catalogId)+"");
                        params.put("ITEM_ID", minPriceItem.getId()+"");
                        

                        VelocityContext context = new VelocityContext();
                        context.put("itemDetails", itemDetails);
                        context.put("params", params);
                        //htmlString = getHtmlFromVelocity(templateFile, context);
                        
                        String exportFileName = Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator + "SearchSnippet.html";
                        File exportFile = new File(exportFileName);
                        if(!exportFile.exists()) {
                                exportFile.createNewFile();
                        }
                        
                        BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(exportFile)));
                        
                        Template template = Velocity.getTemplate(templateFile);
                        template.merge(context, writer);
                        
                        writer.flush();
                        writer.close();
                        Utils.info("Export Complete!");

                        
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
        

        public String getHtmlFromVelocity(String templateFile, VelocityContext context){
                try {
                        Velocity.init("velocity/velocity.properties");
                        Template template = Velocity.getTemplate(templateFile);
                        if(template != null) {
                                StringWriter writer = new StringWriter();
                                template.merge(context, writer);
                                writer.flush();
                                writer.close();
                                return writer.toString();
                        }
        
                        } catch (ResourceNotFoundException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (ParseErrorException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (MethodInvocationException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
        
                return null;
        }


}