Subversion Repositories SmartDukaan

Rev

Rev 6602 | Rev 6622 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2171 rajveer 1
package in.shop2020.util;
3929 mandeep.dh 2
 
2171 rajveer 3
import in.shop2020.metamodel.core.Entity;
4
import in.shop2020.metamodel.core.EntityState;
5
import in.shop2020.metamodel.core.EntityStatus;
6
import in.shop2020.metamodel.util.CreationUtils;
7
import in.shop2020.metamodel.util.ExpandedEntity;
5945 mandeep.dh 8
import in.shop2020.model.v1.catalog.CatalogService.Client;
2171 rajveer 9
import in.shop2020.model.v1.catalog.Item;
6602 amit.gupta 10
import in.shop2020.model.v1.catalog.ItemShippingInfo;
3560 rajveer 11
import in.shop2020.model.v1.catalog.Source;
2171 rajveer 12
import in.shop2020.model.v1.catalog.status;
3127 rajveer 13
import in.shop2020.thrift.clients.CatalogClient;
3083 vikas 14
import in.shop2020.ui.util.CatalogUploderToGAE;
2733 rajveer 15
import in.shop2020.ui.util.ComparisonStatsFetcher;
3083 vikas 16
import in.shop2020.ui.util.NewVUI;
2367 rajveer 17
import in.shop2020.ui.util.PriceInsertor;
2838 mandeep.dh 18
import in.shop2020.ui.util.SpecialPageJSONConvertor;
6602 amit.gupta 19
import in.shop2020.utils.ConfigClientKeys;
3464 rajveer 20
import in.shop2020.utils.GmailUtils;
2171 rajveer 21
 
3083 vikas 22
import java.io.File;
23
import java.io.IOException;
4098 anupam.sin 24
import java.text.SimpleDateFormat;
3083 vikas 25
import java.util.ArrayList;
26
import java.util.Calendar;
27
import java.util.Date;
28
import java.util.HashMap;
5404 amit.gupta 29
import java.util.HashSet;
5479 amit.gupta 30
import java.util.Iterator;
3083 vikas 31
import java.util.LinkedHashMap;
32
import java.util.List;
33
import java.util.Map;
2171 rajveer 34
 
3464 rajveer 35
import javax.mail.MessagingException;
36
 
3083 vikas 37
import org.apache.commons.cli.CommandLine;
38
import org.apache.commons.cli.CommandLineParser;
39
import org.apache.commons.cli.HelpFormatter;
40
import org.apache.commons.cli.Options;
41
import org.apache.commons.cli.ParseException;
42
import org.apache.commons.cli.PosixParser;
5227 amit.gupta 43
import org.apache.commons.lang.StringUtils;
3929 mandeep.dh 44
import org.apache.commons.logging.Log;
45
import org.apache.commons.logging.LogFactory;
6602 amit.gupta 46
import org.apache.thrift.transport.TTransportException;
2171 rajveer 47
 
5084 phani.kuma 48
import com.google.gson.Gson;
49
 
3929 mandeep.dh 50
public class ContentGenerationUtility {
51
    private static final String   UPDATE_TYPE_CATALOG         = "CATALOG";
2171 rajveer 52
 
3929 mandeep.dh 53
    private static final String   UPDATE_TYPE_CONTENT         = "CONTENT";
3083 vikas 54
 
4098 anupam.sin 55
    private static final String   COMMAND_LINE                = "java ContentGenerationUtility.class -t { ALL | INCREMENTAL | ONE } -s { yyyy-MM-dd-HH-mm-ss } -u { CONTENT | CATALOG } -e {EntityId} ";
3929 mandeep.dh 56
 
57
    private static Log            log                         = LogFactory
58
                                                                      .getLog(ContentGenerationUtility.class);
5227 amit.gupta 59
    private static long 			ONE_DAY					  = 24*60*60*1000;  	//milliseconds in a day						 	
3929 mandeep.dh 60
    // Commandline options
61
    private static Options        options                     = null;
62
    private static final String   GENERATION_TYPE_INCREMENTAL = "INCREMENTAL";
63
    private static final String   GENERATION_TYPE_ALL         = "ALL";
64
    private static final String   GENERATION_TYPE_ONE         = "ONE";
65
    private static final String   UPDATE_TYPE_OPTION          = "u";
66
    private static final String   GENERATION_TYPE_OPTION      = "t";
67
    private static final String   ENTITY_ID_OPTION            = "e";
4098 anupam.sin 68
    private static final String   TIMESTAMP_OPTION            = "s";
3929 mandeep.dh 69
 
70
    // Default values of cmdline options
71
    private static String         UPDATE_TYPE                 = UPDATE_TYPE_CONTENT;
72
    private static String         GENERATION_TYPE             = GENERATION_TYPE_INCREMENTAL;
73
    private static String         ENTITY_ID                   = "ALL";
5664 amit.gupta 74
    private static String [] 	  DOMAINPATHS 			      = Utils.DOMAIN_NAMES_FOR_CONTENT_GENERATION.split(";");
3929 mandeep.dh 75
 
4098 anupam.sin 76
    private Date 				  timeStamp			  		  = null;
3929 mandeep.dh 77
    private CommandLine           cmd                         = null;
78
    private Map<Long, List<Item>> entityIdItemMap             = new LinkedHashMap<Long, List<Item>>();
5404 amit.gupta 79
    private List<Long> 			  allValidEntityIds 			  = null;
3929 mandeep.dh 80
    private Long                  lastGenerationTime          = 0l;
81
    private Map<Long, Entity>     entities;
82
    private List<Item>            items;
83
    private List<Source>          sources;
84
    private CatalogClient         csc;
85
    private Client                client;
5279 amit.gupta 86
    private List<Item>			  alertItems;	
3929 mandeep.dh 87
    private long                  newLastGenerationTime;
88
 
89
    static {
2171 rajveer 90
        options = new Options();
91
        options.addOption(GENERATION_TYPE_OPTION, true, "Generation type");
3929 mandeep.dh 92
        options.addOption(UPDATE_TYPE_OPTION, true, "Default is : "
93
                + UPDATE_TYPE);
94
        options.addOption(ENTITY_ID_OPTION, true, "all entities " + ENTITY_ID
95
                + " by default");
4098 anupam.sin 96
        options.addOption(TIMESTAMP_OPTION, true, "Manual timestamp");
97
 
2171 rajveer 98
    }
3929 mandeep.dh 99
 
100
    public ContentGenerationUtility() throws Exception {
3127 rajveer 101
        csc = new CatalogClient();
2171 rajveer 102
        client = csc.getClient();
3573 rajveer 103
        sources = client.getAllSources();
5279 amit.gupta 104
        alertItems = new ArrayList<Item>();	
2171 rajveer 105
    }
2367 rajveer 106
 
2171 rajveer 107
    /**
108
     * @param args
3929 mandeep.dh 109
     * @throws Exception
2171 rajveer 110
     */
3929 mandeep.dh 111
    public static void main(String[] args) throws Exception {
6192 amit.gupta 112
        ContentGenerationUtility cgu = new ContentGenerationUtility();
113
 
114
        // Load arguments
115
        cgu.loadArgs(args);
116
 
117
        // Call method based on arguments
118
        cgu.callMethod();
2171 rajveer 119
    }
2367 rajveer 120
 
3929 mandeep.dh 121
    /**
122
     * Validate and set command line arguments. Exit after printing usage if
123
     * anything is astray
124
     * 
125
     * @param args
126
     *            String[] args as featured in public static void main()
2171 rajveer 127
     */
3929 mandeep.dh 128
    private void loadArgs(String[] args) {
2171 rajveer 129
        CommandLineParser parser = new PosixParser();
3929 mandeep.dh 130
 
2171 rajveer 131
        try {
132
            cmd = parser.parse(options, args);
133
        } catch (ParseException e) {
3929 mandeep.dh 134
            log.error("Error parsing arguments", e);
2171 rajveer 135
            System.exit(1);
136
        }
3929 mandeep.dh 137
 
2171 rajveer 138
        // Check for mandatory args
3929 mandeep.dh 139
        if (!(cmd.hasOption(GENERATION_TYPE_OPTION) && cmd
140
                .hasOption(UPDATE_TYPE_OPTION))) {
2171 rajveer 141
            HelpFormatter formatter = new HelpFormatter();
3929 mandeep.dh 142
            formatter.printHelp(COMMAND_LINE, options);
2171 rajveer 143
            System.exit(1);
144
        }
4098 anupam.sin 145
 
146
 
2171 rajveer 147
        GENERATION_TYPE = cmd.getOptionValue(GENERATION_TYPE_OPTION);
4098 anupam.sin 148
 
2367 rajveer 149
        UPDATE_TYPE = cmd.getOptionValue(UPDATE_TYPE_OPTION);
3929 mandeep.dh 150
 
2171 rajveer 151
        // Look for optional args.
3929 mandeep.dh 152
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
153
            if (cmd.hasOption(ENTITY_ID_OPTION)) {
2171 rajveer 154
                ENTITY_ID = cmd.getOptionValue(ENTITY_ID_OPTION);
3929 mandeep.dh 155
            } else {
2171 rajveer 156
                HelpFormatter formatter = new HelpFormatter();
3929 mandeep.dh 157
                formatter.printHelp(COMMAND_LINE, options);
2171 rajveer 158
                System.exit(1);
159
            }
160
        }
4098 anupam.sin 161
 
162
        if (GENERATION_TYPE_INCREMENTAL.equals(GENERATION_TYPE))
163
        	if (cmd.hasOption(TIMESTAMP_OPTION)) {
164
        		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
165
        		try {
166
        		    timeStamp = df.parse(cmd.getOptionValue(TIMESTAMP_OPTION));
167
        		} catch(Exception e) {
168
        			HelpFormatter formatter = new HelpFormatter();
169
                    formatter.printHelp(COMMAND_LINE, options);
170
                    System.exit(1);
171
        		}
172
        	}
2367 rajveer 173
    }
3929 mandeep.dh 174
 
2367 rajveer 175
    /**
176
     * Call method based on arguments
3929 mandeep.dh 177
     * 
2367 rajveer 178
     * @throws Exception
179
     */
3929 mandeep.dh 180
    private void callMethod() {
181
        boolean isSuccess = false;
182
        String logfile = "/tmp/content-from-cms.log";
183
        if (UPDATE_TYPE.equals(UPDATE_TYPE_CONTENT)) {
184
            logfile = "/tmp/content-from-cms.log";
185
            try {
186
                this.generateContent();
187
                isSuccess = true;
188
            } catch (Exception e) {
189
                log.error("Error generating content", e);
190
            }
191
        }
192
 
193
        if (UPDATE_TYPE.equals(UPDATE_TYPE_CATALOG)) {
194
            logfile = "/tmp/content-from-catalog.log";
195
            try {
196
                this.updatePrices();
197
                isSuccess = true;
198
            } catch (Exception e) {
199
                log.error("Error updating prices", e);
200
            }
201
        }
202
 
4969 amit.gupta 203
        GmailUtils gm = new GmailUtils();
5058 amit.gupta 204
        String[] sendTo = { "rajveer.singh@shop2020.in", "mandeep.dhir@shop2020.in", "pankaj.kankar@shop2020.in", "anupam.singh@shop2020.in", "amit.gupta@shop2020.in" };
4099 anupam.sin 205
 
206
        try {
207
            gm.sendSSLMessage(sendTo, "Content Generation Successful ? : "
208
                    + isSuccess, "Content generation completed at time : "
209
                    + Calendar.getInstance().getTime().toString(),
4311 rajveer 210
                    "build@shop2020.in", "cafe@nes", logfile);
4099 anupam.sin 211
        } catch (MessagingException e) {
212
            log.error("Could not send status mail", e);
4969 amit.gupta 213
        }
2367 rajveer 214
    }
215
 
3929 mandeep.dh 216
    public boolean cleanDir(File dir, boolean deleteSelf) {
217
        if (dir.isDirectory()) {
218
            String[] children = dir.list();
219
            for (int i = 0; i < children.length; i++) {
220
                boolean success = cleanDir(new File(dir, children[i]), true);
221
                if (!success) {
222
                    return false;
223
                }
224
            }
225
        }
226
 
227
        // The directory is now empty so delete it
228
        if (deleteSelf) {
229
            return dir.delete();
230
        }
231
 
232
        return true;
233
    }
234
 
235
    private void removeOldResources() throws IOException {
236
        File f = new File(Utils.EXPORT_SOLR_PATH);
237
        if (f.exists()) {
238
            cleanDir(f, false);
239
        }
5664 amit.gupta 240
 
241
        for(String domainPath : DOMAINPATHS){
242
        	String pathName = domainPath.split("\\.")[0].split(":")[0];
243
        	File f1 = new File(Utils.EXPORT_PATH + "html/entities-" +  pathName);
244
        	if (f1.exists()) {
245
        		cleanDir(f1, false);
246
        	}else {
247
        		f1.mkdir();
248
        	}
3929 mandeep.dh 249
        }
250
    }
251
 
2367 rajveer 252
    /**
253
     * Update the prices in the generated content
3929 mandeep.dh 254
     * 
2367 rajveer 255
     * @throws Exception
256
     */
257
    private void updatePrices() throws Exception {
3929 mandeep.dh 258
        lastGenerationTime = new Long(0);
259
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
2367 rajveer 260
            items = client.getItemsByCatalogId(Long.parseLong(ENTITY_ID));
5479 amit.gupta 261
            Iterator<Item> it = items.iterator();
262
            while(it.hasNext()){
263
            	status st = it.next().getItemStatus();
264
            	if(!(st.equals(status.ACTIVE) || st.equals(status.PAUSED) || 
265
            				st.equals(status.COMING_SOON) || st.equals(status.PHASED_OUT))){
266
            		it.remove();
267
            	}
268
            }
269
            try {
270
            	//Generate prices and availability data for amazon
271
            	AmazonSCDataGenerator.generatePricesAndAvailability(items);
272
            } catch (Exception e) {
273
            	log.info("Could not generate Amazon prices and availability", e);
274
            }
6274 amit.gupta 275
            //ProductListGenerator.updatePriceForEntity(Long.parseLong(ENTITY_ID), items.get(0).getSellingPrice(), items.get(0).getMrp());
3929 mandeep.dh 276
        } else {
2367 rajveer 277
            items = client.getAllItemsByStatus(status.ACTIVE);
5227 amit.gupta 278
            items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
2367 rajveer 279
            items.addAll(client.getAllItemsByStatus(status.PAUSED));
3929 mandeep.dh 280
            // Clean up the data from the solr directories.
2367 rajveer 281
            removeOldResources();
282
 
283
        }
3929 mandeep.dh 284
 
285
        // this still needs to be evolved. Must not be used.
286
        if (GENERATION_TYPE.equals(GENERATION_TYPE_INCREMENTAL)) {
2367 rajveer 287
        }
288
 
3929 mandeep.dh 289
        // Populate the entityIdIemMap
290
        populateEntityIdItemMap();
6602 amit.gupta 291
        List<Long> inStockEntities = null;
292
        // Generate partners and json objects for phones only
293
        if (!GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
294
        	ProductListGenerator generator = new ProductListGenerator(entityIdItemMap);
295
        	generator.generateThinkDigitFeed();
296
        	inStockEntities = generator.getInStockCatalogItemIds();
297
        	generator.generateProductsListXML();
298
        	generator.generateAccessoriesXML();
299
        	generator.generateCamerasXML();
300
        	generator.generateProductListJavascript();
301
 
302
        	try	{
303
        		generator.generateProductXMLForDisplayAds();
304
        	} catch (Exception e) {
305
 
306
        	}
307
 
308
        }
2367 rajveer 309
        PriceInsertor priceInserter = new PriceInsertor();
310
 
3929 mandeep.dh 311
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
312
            long entityId = entry.getKey();
313
            List<Item> items = entry.getValue();
5664 amit.gupta 314
	            // TODO Domain name and destination directory should be read from
315
	            // properties file
316
            double minPrice = 0d;
6602 amit.gupta 317
            String availability = "In Stock";
318
            if (inStockEntities != null ) {
319
            	if (!inStockEntities.contains(entry.getKey())) {
320
            		availability = "Out of Stock";
321
            	}
322
            } else {
323
            	availability = getAvaialability(entry.getValue());
324
            }
5664 amit.gupta 325
            StringBuilder priceString = new StringBuilder();
6602 amit.gupta 326
            StringBuilder availabilityString = new StringBuilder();
5664 amit.gupta 327
            boolean domainOnce = true;
5669 amit.gupta 328
            boolean sourceOnce = true;
5664 amit.gupta 329
            for(String domainPath : DOMAINPATHS){
330
            	String domainName = domainPath;
331
            	String pathName = domainPath.split("\\.")[0].split(":")[0];
332
            	minPrice = priceInserter.insertPriceInHtml(items, entityId,
333
            			domainName, Utils.EXPORT_PATH + "html/entities-" +  pathName + "/", null);
334
            	if(domainOnce){
6602 amit.gupta 335
            		priceString.append("<field name=\"F_50002\">" + minPrice + "</field>");
6607 amit.gupta 336
            		availabilityString.append("<field name=\"F_50028\">" + availability + "</field>");
5664 amit.gupta 337
            		domainOnce = false;
338
            	}
339
            	if(sources != null){
340
            		for (Source source : sources) {
341
                        minPrice = priceInserter.insertPriceInHtml(items, entityId,
342
                                domainName, Utils.EXPORT_PATH + "html/entities-" + pathName + "/",
343
                                source);
344
                        if(sourceOnce){
345
                        	priceString.append("<field name=\"F_50002_"
346
                                + source.getId() + "\">" + minPrice + "</field>");
6602 amit.gupta 347
                        	availabilityString.append("<field name=\"F_50028_"
348
                        			+ source.getId() + "\">" + availability + "</field>");
5664 amit.gupta 349
                        }
350
            		}
5669 amit.gupta 351
            		sourceOnce = false;
5664 amit.gupta 352
            	}
2367 rajveer 353
            }
3929 mandeep.dh 354
 
355
            priceInserter.insertPriceInSolrData(entityId,
6602 amit.gupta 356
                    priceString.toString(), availabilityString.toString());
2367 rajveer 357
        }
3929 mandeep.dh 358
 
4058 rajveer 359
        priceInserter.copySolrSchemaFiles();
5084 phani.kuma 360
        synonymTitlesExporter();
2367 rajveer 361
    }
362
 
6602 amit.gupta 363
    private String getAvaialability(List<Item> value) {
364
    	boolean isActive = true;
365
    	try {
366
			Client catalogClientProd = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(), ConfigClientKeys.catalog_service_server_port.toString()).getClient();
367
			for (Item item : value ) {
368
				if (item.getItemStatus().equals(status.ACTIVE)) {
369
					if(item.isRisky()){
370
	    				try {
371
	    					ItemShippingInfo isi = catalogClientProd.isActive(item.getId());
372
	    					isActive = isi.isIsActive();
373
	    				} catch (Exception e) {
374
	    					e.printStackTrace();
375
	    					isActive = true;
376
	    				}
377
	    			}
378
				}
379
				if(isActive) break;
380
			}
381
		} catch (TTransportException e) {
382
			// TODO Auto-generated catch block
383
			e.printStackTrace();
384
		}
385
		return isActive ? "In Stock" : "Out of Stock";
386
	}
387
 
388
	/**
2171 rajveer 389
     * Generates content for the specified entity embedding links to the
390
     * specified domain name.
391
     * 
3929 mandeep.dh 392
     * The method will not generate content if one of the following conditions
393
     * is met:
2171 rajveer 394
     * <ol>
395
     * <li>The entity is not ready.
396
     * <li>The category has not been updated yet. (Set to -1).
2367 rajveer 397
     * <li>The content has not been updated.
2171 rajveer 398
     * </ol>
3929 mandeep.dh 399
     * 
2367 rajveer 400
     * @throws
2171 rajveer 401
     */
3929 mandeep.dh 402
    private void generateContent() throws Exception {
403
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL)) {
404
            entities = CreationUtils.getEntities();
2367 rajveer 405
            lastGenerationTime = new Long(0);
3929 mandeep.dh 406
        } else if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
407
            entities = new HashMap<Long, Entity>();
408
            entities.put(Long.parseLong(ENTITY_ID),
409
                    CreationUtils.getEntity(Long.parseLong(ENTITY_ID)));
410
            lastGenerationTime = new Long(0);
411
        } else {
4098 anupam.sin 412
        	entities = CreationUtils.getEntities();
413
            //  When we read lastGenerationTime from database
414
            //  then only we should mark the 
415
            //	current time as newLastGenerationTime
416
            if(timeStamp == null) {
417
            	newLastGenerationTime = new Date().getTime();
418
            	lastGenerationTime = CreationUtils.getLastContentGenerationTime();
419
            } else {
420
            	lastGenerationTime = timeStamp.getTime();
421
            }
422
 
3929 mandeep.dh 423
            log.info("lastGenerationTime: " + lastGenerationTime);
424
            if (lastGenerationTime == null) {
2171 rajveer 425
                lastGenerationTime = new Long(0);
3929 mandeep.dh 426
            }
4098 anupam.sin 427
        } 
3929 mandeep.dh 428
 
429
        // Filter invalid entities here
2367 rajveer 430
        List<Entity> validEntities = new ArrayList<Entity>();
3929 mandeep.dh 431
        for (long entityID : entities.keySet()) {
432
            if (isValidEntity(entities.get(entityID))) {
433
                validEntities.add(entities.get(entityID));
434
            }
2171 rajveer 435
        }
3929 mandeep.dh 436
 
437
        // Calculate comparison scores
438
        log.info("Calculating comparison scores");
2367 rajveer 439
        NewCMP cmp = new NewCMP(validEntities);
2171 rajveer 440
        Map<Long, Map<Long, Double>> slideScoresByEntity = cmp.getSlideScores();
2367 rajveer 441
        CreationUtils.storeSlideScores(slideScoresByEntity);
2658 rajveer 442
 
3516 rajveer 443
        // Fetch comparison statistics everyday and store them in BDB
3929 mandeep.dh 444
        log.info("Fetching comparison statistics");
3516 rajveer 445
        ComparisonStatsFetcher csf = new ComparisonStatsFetcher();
446
        csf.fetchAndStoreComparisonStats();
3929 mandeep.dh 447
 
448
        // Upload catalog to Google App Engine.
449
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL)) {
450
            log.info("Uploading Catalog to Google app engine");
3083 vikas 451
            List<Item> allItems = client.getAllItems(false);
452
            allItems.addAll(client.getAllItems(true));
453
            CatalogUploderToGAE catalogUploaderToGAE = new CatalogUploderToGAE();
454
            catalogUploaderToGAE.uploadItems(allItems);
455
        }
3929 mandeep.dh 456
 
2726 rajveer 457
        items = client.getAllItemsByStatus(status.ACTIVE);
458
        items.addAll(client.getAllItemsByStatus(status.PAUSED));
459
        items.addAll(client.getAllItemsByStatus(status.CONTENT_COMPLETE));
5227 amit.gupta 460
        items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
2726 rajveer 461
        populateEntityIdItemMap();
3929 mandeep.dh 462
 
4677 rajveer 463
        //FIXME Avoiding the finding of accesories, as list of categories for which we need to find accessories is hardocoded in code. 
464
        // We need to make that configurable. Also creating ticket to improve it.
5106 rajveer 465
        try{
466
	        log.info("Finding accessories");
5404 amit.gupta 467
	        AccessoriesFinder af = new AccessoriesFinder(new HashSet<Long>(allValidEntityIds));
5106 rajveer 468
	        Map<Long, Map<Long, List<Long>>> relatedAccessories = af.findAccessories();
469
	        CreationUtils.storeRelatedAccessories(relatedAccessories);
470
        }catch (Exception e) {
471
        	log.error("Error while generating accessories" + e);
472
		}
4677 rajveer 473
 
3929 mandeep.dh 474
        log.info("Writing JSON file for special pages");
2838 mandeep.dh 475
        SpecialPageJSONConvertor bjc = new SpecialPageJSONConvertor();
3929 mandeep.dh 476
        bjc.writeToJSONFile(new File(Utils.EXPORT_JAVASCRIPT_CONTENT_PATH
477
                + "special-pages.json"));
2838 mandeep.dh 478
 
3929 mandeep.dh 479
        log.info("Generating velocity templates, images, documents etc.");
2171 rajveer 480
        NewVUI vui = new NewVUI(lastGenerationTime);
3929 mandeep.dh 481
        for (Entity entity : validEntities) {
482
            log.info("Processing Entityid: " + entity.getID());
483
            vui.generateContentForOneEntity(entity, Utils.EXPORT_VELOCITY_PATH);
2171 rajveer 484
        }
3929 mandeep.dh 485
 
486
        // Generate synonyms list. This will be used in PriceComparisonTool to
487
        // resolve the product names.
488
        log.info("Generating synonyms");
5084 phani.kuma 489
        SynonymExporter sx = new SynonymExporter();
490
        sx.storeSynonyms(validEntities);
5004 varun.gupt 491
 
5155 varun.gupt 492
        List<Entity> allValidEntities;
493
 
494
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL))	{
495
        	allValidEntities = validEntities;
496
 
497
        } else	{
498
        	allValidEntities = new ArrayList<Entity>();
5404 amit.gupta 499
			for (Long entityId : allValidEntityIds)	{
500
				allValidEntities.add(CreationUtils.getEntity(entityId));
5155 varun.gupt 501
			}
502
        }
503
 
5004 varun.gupt 504
        log.info("Generating HTML for Site Index");
5155 varun.gupt 505
        ProductIndexGenerator indexGenerator = new ProductIndexGenerator(allValidEntities);
5004 varun.gupt 506
        indexGenerator.generate();
5642 amit.gupta 507
 
508
        log.info("Generating HTML for Site for Product Documents");
509
        ProductDocumentsGenerator asGenerator = new ProductDocumentsGenerator(allValidEntities);
510
        asGenerator.generate();
5004 varun.gupt 511
 
5117 varun.gupt 512
        log.info("Generating HTML for Accessories Compatibility Index");
5155 varun.gupt 513
        CompatibleAccessoriesIndexGenerator generator = new CompatibleAccessoriesIndexGenerator(allValidEntities);
5117 varun.gupt 514
        generator.generate();
5600 amit.gupta 515
 
5604 amit.gupta 516
        log.info("Generating HTML for Most Frequently searched keywords");
5600 amit.gupta 517
        MostFrequentlySearchedKeywords mfsk = new MostFrequentlySearchedKeywords();
5604 amit.gupta 518
        mfsk.generate();
5117 varun.gupt 519
 
5315 varun.gupt 520
        log.info("Generating HTML for Most Compared Index");
5425 amit.gupta 521
        MostComparedIndexGenerator mostCompGenerator = new MostComparedIndexGenerator(allValidEntityIds);
5315 varun.gupt 522
        mostCompGenerator.generate();
5522 varun.gupt 523
 
524
        log.info("Generating XML for Mobile Site XML feed");
525
        MobileSiteDataXMLGenerator mSiteXMLGenerator = new MobileSiteDataXMLGenerator(allValidEntities);
526
        mSiteXMLGenerator.generate();
5315 varun.gupt 527
 
3929 mandeep.dh 528
        if (newLastGenerationTime != 0) {
529
            CreationUtils.storeLastContentGenerationTime(newLastGenerationTime);
530
        }
531
 
532
 
533
        log.info("Generating Solr files");
2367 rajveer 534
        NewIR ir = new NewIR(validEntities);
2227 rajveer 535
        ir.exportIRData();
3929 mandeep.dh 536
        // ir.transformIrDataXMLtoSolrXML();
2227 rajveer 537
        ir.exportIRMetaData();
4057 rajveer 538
        ir.transformIrMetaDataXMLtoSolrSchemaXML();
539
        ir.transformIrMetaDataXMLtoSolrCatchAllXML();
2227 rajveer 540
 
3929 mandeep.dh 541
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
542
            List<Item> items = entry.getValue();
543
            for (Item item : items) {
5227 amit.gupta 544
                if (item.getItemStatus() == status.CONTENT_COMPLETE || item.getItemStatus() == status.COMING_SOON) {
5360 amit.gupta 545
                	if(item.getStartDate() <= new Date().getTime() + ONE_DAY){
5227 amit.gupta 546
                		item.setItemStatus(status.ACTIVE);
547
                		item.setStatus_description("This item is active");
548
                	} else {
549
                		item.setItemStatus(status.COMING_SOON);
550
                		String productName = getProductName(item);
551
                		String statusDescription = productName + " is coming soon.";
552
                		if(item.getExpectedArrivalDate()>new Date().getTime() + ONE_DAY){
553
                			statusDescription = productName + " will be available by " 
554
                			+ new SimpleDateFormat("dd/MM/yy").format(new Date(item.getExpectedArrivalDate()));
555
                		}
5279 amit.gupta 556
                		//Send alert to Category team one day before expected arrival date
557
                		//So they may change the expected arrival date if they want to.
558
                		if(item.getExpectedArrivalDate() < new Date().getTime() + 2*ONE_DAY && 
559
                				item.getExpectedArrivalDate() > new Date().getTime() + ONE_DAY) {
560
                				alertItems.add(item);
561
                		}
5227 amit.gupta 562
                		item.setStatus_description(statusDescription);
563
                	}
2493 rajveer 564
                    client.updateItem(item);
5279 amit.gupta 565
            	}
3929 mandeep.dh 566
            }
2493 rajveer 567
        }
5279 amit.gupta 568
        sendAlertToCategoryTeam(alertItems);
4472 mandeep.dh 569
        try {
570
            //generate products list that is to be uploaded in Amazon.
5901 amit.gupta 571
        	AmazonSCDataGenerator ascdGenerator = new AmazonSCDataGenerator(validEntities, GENERATION_TYPE);
572
            ascdGenerator.generateSCProdData();
4472 mandeep.dh 573
        } catch (Exception e) {
4994 amit.gupta 574
        	e.printStackTrace();
4640 mandeep.dh 575
            log.info("Could not generate Amazon data", e);
4472 mandeep.dh 576
        }
2171 rajveer 577
    }
2367 rajveer 578
 
5279 amit.gupta 579
    private void sendAlertToCategoryTeam(List<Item> items) {
580
    	if(items!=null && items.size()!=0){
581
			GmailUtils util = new GmailUtils();
5280 amit.gupta 582
			String[] recipients = {"amit.gupta@shop2020.in", "chaitnaya.vats@shop2020.in", "ashutosh.saxena@shop2020.in"};
5279 amit.gupta 583
			String from = "build@shop2020.in";
584
			String password = "cafe@nes";
585
			String subject = Utils.EXPECTED_ARRIVAL_ACHIEVED_TEMPLATE;
586
			StringBuffer message = new StringBuffer("Please check the following items:\n");
587
			List<File> emptyList = new ArrayList<File>();
588
			for( Item item : items){
589
				message.append("\t" + getProductName(item));
590
			}
591
			try {
592
				util.sendSSLMessage(recipients, subject, message.toString(), from, password, emptyList);
593
			} catch (Exception e){
594
				log.info("Could not send alert" + e);
595
			}
596
    	}
597
	}
598
 
599
	private String getProductName(Item item) {
5227 amit.gupta 600
    	String brand = item.getBrand();
601
		String modelName = item.getModelName();
602
		String modelNumber = item.getModelNumber();
603
		String product = "";
604
		if(StringUtils.isEmpty(modelName)){
605
			product = brand + " " + modelNumber;
606
		}else {
607
			product = brand + " " + modelName + " " + modelNumber;
608
		}
609
		return product;
610
	}
611
 
2171 rajveer 612
    /**
3929 mandeep.dh 613
     * Checks weather entity is valid or not. Entity will be invalid in one of
614
     * these cases:
2367 rajveer 615
     * <ol>
616
     * <li>The entity is not ready.
617
     * <li>The category has not been updated yet. (Set to -1).
618
     * <li>Content has not been updated after last content generation timestamp.
619
     * </ol>
620
     * 
621
     * @param entity
622
     * @return
623
     * @throws Exception
2171 rajveer 624
     */
3929 mandeep.dh 625
    private boolean isValidEntity(Entity entity) throws Exception {
2367 rajveer 626
        ExpandedEntity expEntity = new ExpandedEntity(entity);
627
        EntityState state = CreationUtils.getEntityState(entity.getID());
628
        long categoryID = expEntity.getCategoryID();
3929 mandeep.dh 629
 
630
        if (state.getStatus() != EntityStatus.READY || categoryID == -1) {
2367 rajveer 631
            return false;
632
        }
3929 mandeep.dh 633
        if (state.getMerkedReadyOn().getTime() < this.lastGenerationTime) {
2367 rajveer 634
            return false;
635
        }
636
        return true;
637
    }
638
 
3929 mandeep.dh 639
    private void populateEntityIdItemMap() {
2171 rajveer 640
        Date todate = new Date();
4775 mandeep.dh 641
        Utils.info("Processing " + items.size() + " items");
3929 mandeep.dh 642
        for (Item item : items) {
4778 mandeep.dh 643
            Utils.info(item.getId() + ":" + item.getItemStatus() + ":" + item.getCatalogItemId());
3929 mandeep.dh 644
            // TODO Can be removed as we are checking in calling function
645
            if (!(item.getItemStatus() == status.ACTIVE
646
                    || item.getItemStatus() == status.CONTENT_COMPLETE || item
5227 amit.gupta 647
                    .getItemStatus() == status.PAUSED || item.getItemStatus() == status.COMING_SOON)) {
2171 rajveer 648
                continue;
649
            }
4777 mandeep.dh 650
            Utils.info(item.getStartDate() + ":" + item.getSellingPrice());
5227 amit.gupta 651
 
652
			if (todate.getTime() < item.getStartDate()
653
					&& (!item.isSetExpectedArrivalDate() || todate.getTime() < item.getComingSoonStartDate()) 
654
					|| item.getSellingPrice() == 0) {
655
				continue;
656
			}
4777 mandeep.dh 657
            Utils.info(item.getId() + " Item is adding");
2367 rajveer 658
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
3929 mandeep.dh 659
            if (itemList == null) {
2171 rajveer 660
                itemList = new ArrayList<Item>();
5227 amit.gupta 661
            } 
2171 rajveer 662
            itemList.add(item);
663
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
664
        }
2367 rajveer 665
 
4775 mandeep.dh 666
        Utils.info("Processing " + entityIdItemMap.size() + " entities");
3929 mandeep.dh 667
        // Remove all items which have not been updated since last content
668
        // generation.
2171 rajveer 669
        List<Long> removeEntities = new ArrayList<Long>();
3929 mandeep.dh 670
        for (Long entityId : entityIdItemMap.keySet()) {
2171 rajveer 671
            boolean isValidEntity = false;
3929 mandeep.dh 672
            // If any one of the items has been updated before current
673
            // timestamp, than we generate content for whole entity
674
            for (Item item : entityIdItemMap.get(entityId)) {
5227 amit.gupta 675
                if (item.getUpdatedOn() > lastGenerationTime || item.getItemStatus()==status.COMING_SOON) {
2171 rajveer 676
                    isValidEntity = true;
677
                }
678
            }
3929 mandeep.dh 679
            if (!isValidEntity) {
2171 rajveer 680
                removeEntities.add(entityId);
681
            }
682
        }
5404 amit.gupta 683
        //Simply assign allValidEntityIds to a class variable as these need to be used where all valid entites
684
        //are needed.
685
        allValidEntityIds = new ArrayList<Long>(entityIdItemMap.keySet());
3929 mandeep.dh 686
        for (Long entityId : removeEntities) {
2171 rajveer 687
            entityIdItemMap.remove(entityId);
688
        }
4775 mandeep.dh 689
 
690
        Utils.info("Final valid entities to be processed: " + entityIdItemMap.size());
2171 rajveer 691
    }
5084 phani.kuma 692
 
693
    private void synonymTitlesExporter() {
694
    	SynonymExporter sx = new SynonymExporter();
695
        Map<Long, Map<String,List<String>>> synonyms = sx.getSynonyms();
5453 phani.kuma 696
        Map<String, List<String>> finalsynonyms = new HashMap<String, List<String>>();
5084 phani.kuma 697
    	for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
698
            long entityId = entry.getKey();
699
	    	try{
700
	            String brand = "";
5453 phani.kuma 701
	            String originalModelName = "";
702
	            String originalModelNumber = "";
5084 phani.kuma 703
	            List<String> modelNameSynonyms =  new ArrayList<String>();
704
	            List<String> modelNumberSynonyms =  new ArrayList<String>();
705
	            List<String> titles = new ArrayList<String>();
706
	            Map<String,List<String>> synonymMap = synonyms.get(entityId);
707
	            if(synonymMap != null && !synonymMap.isEmpty()){
708
	            	if(synonymMap.get("ORIGINAL_MODEL_NAME") != null && !synonymMap.get("ORIGINAL_MODEL_NAME").isEmpty()){
709
	            		modelNameSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NAME"));
5453 phani.kuma 710
	            		originalModelName = synonymMap.get("ORIGINAL_MODEL_NAME").get(0);
5084 phani.kuma 711
	            	}
712
	            	if(synonymMap.get("MODEL_NAME") != null && !synonymMap.get("MODEL_NAME").isEmpty()){
713
	            		modelNameSynonyms.addAll(synonymMap.get("MODEL_NAME"));
714
	            	}
715
	            	if(synonymMap.get("ORIGINAL_MODEL_NUMBER") != null && !synonymMap.get("ORIGINAL_MODEL_NUMBER").isEmpty()){
716
	            		modelNumberSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NUMBER"));
5453 phani.kuma 717
	            		originalModelNumber = synonymMap.get("ORIGINAL_MODEL_NUMBER").get(0);
5084 phani.kuma 718
	            	}
719
	            	if(synonymMap.get("MODEL_NUMBER") != null && !synonymMap.get("MODEL_NUMBER").isEmpty()){
720
	            		modelNumberSynonyms.addAll(synonymMap.get("MODEL_NUMBER"));
721
	            	}
722
	            	brand = ((synonymMap.get("ORIGINAL_BRAND") != null && !synonymMap.get("ORIGINAL_BRAND").isEmpty()) ? synonymMap.get("ORIGINAL_BRAND").get(0) : "");
723
	            }
724
	            for(String model_name: modelNameSynonyms){
725
	            	for(String model_number: modelNumberSynonyms){
726
	            		String title = brand + " " + model_name + " " + model_number;
727
	            		title = title.replaceAll("  ", " ");
728
	            		titles.add(title);
729
	            	}
730
	            }
5453 phani.kuma 731
	            String originaltitle = brand + " " + originalModelName + " " + originalModelNumber;
732
	            originaltitle = originaltitle.replaceAll("  ", " ");
733
	            originaltitle = originaltitle.trim();
734
	            if(!originaltitle.isEmpty()) {
735
	            	finalsynonyms.put(originaltitle, titles);
736
	            }
5084 phani.kuma 737
	        } catch (Exception e) {
738
				e.printStackTrace();
739
			}
740
    	}
741
 
742
    	String autosuggestFilename = Utils.EXPORT_JAVASCRIPT_CONTENT_PATH + "autosuggest.json";
743
        Gson gson = new Gson();
744
		try {
745
			DBUtils.store(gson.toJson(finalsynonyms), autosuggestFilename);
746
		} catch (Exception e) {
747
			e.printStackTrace();
748
		}
749
    }
2171 rajveer 750
}