Subversion Repositories SmartDukaan

Rev

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