Subversion Repositories SmartDukaan

Rev

Rev 7279 | Rev 7506 | 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.
7336 amit.gupta 349
            	minPrice = priceInserter.insertPriceInHtml(items, entityId,
350
            			domainName, Utils.EXPORT_PATH + "html/entities-" +  pathName + "/", null);
351
            	if(domainOnce){
352
            		priceString.append("<field name=\"F_50002\">" + minPrice + "</field>");
353
            		availabilityString.append("<field name=\"F_50028\">" + availability + "</field>");
354
            		if(entityTags.containsKey(entityId)) {
355
            			List<String> tags = entityTags.get(entityId);
356
            			for(String tag: tags){
357
            				availabilityString.append("\n<field name=\"F_50029\">" + tag + "</field>");
358
            			}
359
            		}
360
            		if(popularityMap.containsKey(entityId)) {
361
            			availabilityString.append("\n<field name=\"F_50030\">" + popularityMap.get(entityId) + "</field>");
362
            		}else {
363
            			availabilityString.append("\n<field name=\"F_50030\">" + "0" + "</field>");
364
            		}
365
            		domainOnce = false;
5664 amit.gupta 366
            	}
7336 amit.gupta 367
            	if(sources != null){
368
            		for (Source source : sources) {
369
                        minPrice = priceInserter.insertPriceInHtml(items, entityId,
370
                                domainName, Utils.EXPORT_PATH + "html/entities-" + pathName + "/",
371
                                source);
372
                        if(sourceOnce){
373
                        	priceString.append("<field name=\"F_50002_"
374
                                + source.getId() + "\">" + minPrice + "</field>");
375
                        }
376
            		}
377
            		sourceOnce = false;
378
            	}
2367 rajveer 379
            }
3929 mandeep.dh 380
 
381
            priceInserter.insertPriceInSolrData(entityId,
6602 amit.gupta 382
                    priceString.toString(), availabilityString.toString());
2367 rajveer 383
        }
3929 mandeep.dh 384
 
4058 rajveer 385
        priceInserter.copySolrSchemaFiles();
5084 phani.kuma 386
        synonymTitlesExporter();
2367 rajveer 387
    }
388
 
7279 amit.gupta 389
    private boolean isStoreItem(List<Item> items2) {
390
		for (Item item : items2){
391
			if(item.isActiveOnStore()) {
392
				return true;
393
			}
394
		}
395
		return false;
396
	}
397
 
398
	private Map<Long, Integer> getPolularityMap() {
6871 amit.gupta 399
		try {
400
			Reader reader = new FileReader(Utils.EXPORT_PATH + Utils.POPULARITY_JSON);
401
			return new Gson().fromJson(reader, new TypeToken<Map<Long, Integer>>() {}.getType());
402
		} catch (FileNotFoundException e) {
403
			log.error("Could not read popularity file");
404
			e.printStackTrace();
405
			return new HashMap<Long, Integer>();
406
		}
407
 
408
	}
409
 
410
	private String getAvaialability(List<Item> value) {
6602 amit.gupta 411
    	boolean isActive = true;
412
    	try {
413
			Client catalogClientProd = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(), ConfigClientKeys.catalog_service_server_port.toString()).getClient();
414
			for (Item item : value ) {
415
				if (item.getItemStatus().equals(status.ACTIVE)) {
416
					if(item.isRisky()){
417
	    				try {
418
	    					ItemShippingInfo isi = catalogClientProd.isActive(item.getId());
419
	    					isActive = isi.isIsActive();
420
	    				} catch (Exception e) {
421
	    					e.printStackTrace();
422
	    					isActive = true;
423
	    				}
424
	    			}
425
				}
426
				if(isActive) break;
427
			}
428
		} catch (TTransportException e) {
429
			// TODO Auto-generated catch block
430
			e.printStackTrace();
431
		}
432
		return isActive ? "In Stock" : "Out of Stock";
433
	}
434
 
435
	/**
2171 rajveer 436
     * Generates content for the specified entity embedding links to the
437
     * specified domain name.
438
     * 
3929 mandeep.dh 439
     * The method will not generate content if one of the following conditions
440
     * is met:
2171 rajveer 441
     * <ol>
442
     * <li>The entity is not ready.
443
     * <li>The category has not been updated yet. (Set to -1).
2367 rajveer 444
     * <li>The content has not been updated.
2171 rajveer 445
     * </ol>
3929 mandeep.dh 446
     * 
2367 rajveer 447
     * @throws
2171 rajveer 448
     */
3929 mandeep.dh 449
    private void generateContent() throws Exception {
450
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL)) {
451
            entities = CreationUtils.getEntities();
2367 rajveer 452
            lastGenerationTime = new Long(0);
3929 mandeep.dh 453
        } else if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
454
            entities = new HashMap<Long, Entity>();
455
            entities.put(Long.parseLong(ENTITY_ID),
456
                    CreationUtils.getEntity(Long.parseLong(ENTITY_ID)));
457
            lastGenerationTime = new Long(0);
458
        } else {
4098 anupam.sin 459
        	entities = CreationUtils.getEntities();
460
            //  When we read lastGenerationTime from database
461
            //  then only we should mark the 
462
            //	current time as newLastGenerationTime
463
            if(timeStamp == null) {
464
            	newLastGenerationTime = new Date().getTime();
465
            	lastGenerationTime = CreationUtils.getLastContentGenerationTime();
466
            } else {
467
            	lastGenerationTime = timeStamp.getTime();
468
            }
469
 
3929 mandeep.dh 470
            log.info("lastGenerationTime: " + lastGenerationTime);
471
            if (lastGenerationTime == null) {
2171 rajveer 472
                lastGenerationTime = new Long(0);
3929 mandeep.dh 473
            }
4098 anupam.sin 474
        } 
3929 mandeep.dh 475
 
476
        // Filter invalid entities here
2367 rajveer 477
        List<Entity> validEntities = new ArrayList<Entity>();
3929 mandeep.dh 478
        for (long entityID : entities.keySet()) {
479
            if (isValidEntity(entities.get(entityID))) {
480
                validEntities.add(entities.get(entityID));
481
            }
2171 rajveer 482
        }
3929 mandeep.dh 483
 
484
        // Calculate comparison scores
485
        log.info("Calculating comparison scores");
2367 rajveer 486
        NewCMP cmp = new NewCMP(validEntities);
2171 rajveer 487
        Map<Long, Map<Long, Double>> slideScoresByEntity = cmp.getSlideScores();
2367 rajveer 488
        CreationUtils.storeSlideScores(slideScoresByEntity);
2658 rajveer 489
 
3516 rajveer 490
        // Fetch comparison statistics everyday and store them in BDB
3929 mandeep.dh 491
        log.info("Fetching comparison statistics");
3516 rajveer 492
        ComparisonStatsFetcher csf = new ComparisonStatsFetcher();
493
        csf.fetchAndStoreComparisonStats();
3929 mandeep.dh 494
 
495
        // Upload catalog to Google App Engine.
496
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL)) {
497
            log.info("Uploading Catalog to Google app engine");
3083 vikas 498
            List<Item> allItems = client.getAllItems(false);
499
            allItems.addAll(client.getAllItems(true));
500
            CatalogUploderToGAE catalogUploaderToGAE = new CatalogUploderToGAE();
501
            catalogUploaderToGAE.uploadItems(allItems);
502
        }
3929 mandeep.dh 503
 
2726 rajveer 504
        items = client.getAllItemsByStatus(status.ACTIVE);
505
        items.addAll(client.getAllItemsByStatus(status.PAUSED));
506
        items.addAll(client.getAllItemsByStatus(status.CONTENT_COMPLETE));
5227 amit.gupta 507
        items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
2726 rajveer 508
        populateEntityIdItemMap();
3929 mandeep.dh 509
 
4677 rajveer 510
        //FIXME Avoiding the finding of accesories, as list of categories for which we need to find accessories is hardocoded in code. 
511
        // We need to make that configurable. Also creating ticket to improve it.
5106 rajveer 512
        try{
513
	        log.info("Finding accessories");
5404 amit.gupta 514
	        AccessoriesFinder af = new AccessoriesFinder(new HashSet<Long>(allValidEntityIds));
5106 rajveer 515
	        Map<Long, Map<Long, List<Long>>> relatedAccessories = af.findAccessories();
516
	        CreationUtils.storeRelatedAccessories(relatedAccessories);
517
        }catch (Exception e) {
518
        	log.error("Error while generating accessories" + e);
519
		}
4677 rajveer 520
 
3929 mandeep.dh 521
        log.info("Writing JSON file for special pages");
2838 mandeep.dh 522
        SpecialPageJSONConvertor bjc = new SpecialPageJSONConvertor();
3929 mandeep.dh 523
        bjc.writeToJSONFile(new File(Utils.EXPORT_JAVASCRIPT_CONTENT_PATH
524
                + "special-pages.json"));
2838 mandeep.dh 525
 
3929 mandeep.dh 526
        log.info("Generating velocity templates, images, documents etc.");
2171 rajveer 527
        NewVUI vui = new NewVUI(lastGenerationTime);
3929 mandeep.dh 528
        for (Entity entity : validEntities) {
529
            log.info("Processing Entityid: " + entity.getID());
530
            vui.generateContentForOneEntity(entity, Utils.EXPORT_VELOCITY_PATH);
2171 rajveer 531
        }
3929 mandeep.dh 532
 
533
        // Generate synonyms list. This will be used in PriceComparisonTool to
534
        // resolve the product names.
535
        log.info("Generating synonyms");
5084 phani.kuma 536
        SynonymExporter sx = new SynonymExporter();
537
        sx.storeSynonyms(validEntities);
5004 varun.gupt 538
 
5155 varun.gupt 539
        List<Entity> allValidEntities;
540
 
541
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL))	{
542
        	allValidEntities = validEntities;
543
 
544
        } else	{
545
        	allValidEntities = new ArrayList<Entity>();
5404 amit.gupta 546
			for (Long entityId : allValidEntityIds)	{
547
				allValidEntities.add(CreationUtils.getEntity(entityId));
5155 varun.gupt 548
			}
549
        }
550
 
5004 varun.gupt 551
        log.info("Generating HTML for Site Index");
5155 varun.gupt 552
        ProductIndexGenerator indexGenerator = new ProductIndexGenerator(allValidEntities);
5004 varun.gupt 553
        indexGenerator.generate();
5642 amit.gupta 554
 
555
        log.info("Generating HTML for Site for Product Documents");
556
        ProductDocumentsGenerator asGenerator = new ProductDocumentsGenerator(allValidEntities);
557
        asGenerator.generate();
5004 varun.gupt 558
 
5117 varun.gupt 559
        log.info("Generating HTML for Accessories Compatibility Index");
5155 varun.gupt 560
        CompatibleAccessoriesIndexGenerator generator = new CompatibleAccessoriesIndexGenerator(allValidEntities);
5117 varun.gupt 561
        generator.generate();
5600 amit.gupta 562
 
5604 amit.gupta 563
        log.info("Generating HTML for Most Frequently searched keywords");
5600 amit.gupta 564
        MostFrequentlySearchedKeywords mfsk = new MostFrequentlySearchedKeywords();
5604 amit.gupta 565
        mfsk.generate();
5117 varun.gupt 566
 
5315 varun.gupt 567
        log.info("Generating HTML for Most Compared Index");
5425 amit.gupta 568
        MostComparedIndexGenerator mostCompGenerator = new MostComparedIndexGenerator(allValidEntityIds);
5315 varun.gupt 569
        mostCompGenerator.generate();
5522 varun.gupt 570
 
571
        log.info("Generating XML for Mobile Site XML feed");
572
        MobileSiteDataXMLGenerator mSiteXMLGenerator = new MobileSiteDataXMLGenerator(allValidEntities);
573
        mSiteXMLGenerator.generate();
5315 varun.gupt 574
 
3929 mandeep.dh 575
        if (newLastGenerationTime != 0) {
576
            CreationUtils.storeLastContentGenerationTime(newLastGenerationTime);
577
        }
578
 
579
 
580
        log.info("Generating Solr files");
2367 rajveer 581
        NewIR ir = new NewIR(validEntities);
2227 rajveer 582
        ir.exportIRData();
3929 mandeep.dh 583
        // ir.transformIrDataXMLtoSolrXML();
2227 rajveer 584
        ir.exportIRMetaData();
4057 rajveer 585
        ir.transformIrMetaDataXMLtoSolrSchemaXML();
586
        ir.transformIrMetaDataXMLtoSolrCatchAllXML();
2227 rajveer 587
 
3929 mandeep.dh 588
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
589
            List<Item> items = entry.getValue();
590
            for (Item item : items) {
5227 amit.gupta 591
                if (item.getItemStatus() == status.CONTENT_COMPLETE || item.getItemStatus() == status.COMING_SOON) {
5360 amit.gupta 592
                	if(item.getStartDate() <= new Date().getTime() + ONE_DAY){
5227 amit.gupta 593
                		item.setItemStatus(status.ACTIVE);
594
                		item.setStatus_description("This item is active");
595
                	} else {
596
                		item.setItemStatus(status.COMING_SOON);
597
                		String productName = getProductName(item);
598
                		String statusDescription = productName + " is coming soon.";
599
                		if(item.getExpectedArrivalDate()>new Date().getTime() + ONE_DAY){
600
                			statusDescription = productName + " will be available by " 
601
                			+ new SimpleDateFormat("dd/MM/yy").format(new Date(item.getExpectedArrivalDate()));
602
                		}
5279 amit.gupta 603
                		//Send alert to Category team one day before expected arrival date
604
                		//So they may change the expected arrival date if they want to.
605
                		if(item.getExpectedArrivalDate() < new Date().getTime() + 2*ONE_DAY && 
606
                				item.getExpectedArrivalDate() > new Date().getTime() + ONE_DAY) {
607
                				alertItems.add(item);
608
                		}
5227 amit.gupta 609
                		item.setStatus_description(statusDescription);
610
                	}
2493 rajveer 611
                    client.updateItem(item);
5279 amit.gupta 612
            	}
3929 mandeep.dh 613
            }
2493 rajveer 614
        }
5279 amit.gupta 615
        sendAlertToCategoryTeam(alertItems);
4472 mandeep.dh 616
        try {
617
            //generate products list that is to be uploaded in Amazon.
5901 amit.gupta 618
        	AmazonSCDataGenerator ascdGenerator = new AmazonSCDataGenerator(validEntities, GENERATION_TYPE);
619
            ascdGenerator.generateSCProdData();
4472 mandeep.dh 620
        } catch (Exception e) {
4994 amit.gupta 621
        	e.printStackTrace();
4640 mandeep.dh 622
            log.info("Could not generate Amazon data", e);
4472 mandeep.dh 623
        }
2171 rajveer 624
    }
2367 rajveer 625
 
5279 amit.gupta 626
    private void sendAlertToCategoryTeam(List<Item> items) {
627
    	if(items!=null && items.size()!=0){
628
			GmailUtils util = new GmailUtils();
6876 amit.gupta 629
			String[] recipients = {"amit.gupta@shop2020.in", "chaitnaya.vats@shop2020.in", "khushal.bhatia@shop2020.in"};
5279 amit.gupta 630
			String from = "build@shop2020.in";
631
			String password = "cafe@nes";
632
			String subject = Utils.EXPECTED_ARRIVAL_ACHIEVED_TEMPLATE;
633
			StringBuffer message = new StringBuffer("Please check the following items:\n");
634
			List<File> emptyList = new ArrayList<File>();
635
			for( Item item : items){
636
				message.append("\t" + getProductName(item));
637
			}
638
			try {
639
				util.sendSSLMessage(recipients, subject, message.toString(), from, password, emptyList);
640
			} catch (Exception e){
641
				log.info("Could not send alert" + e);
642
			}
643
    	}
644
	}
645
 
646
	private String getProductName(Item item) {
5227 amit.gupta 647
    	String brand = item.getBrand();
648
		String modelName = item.getModelName();
649
		String modelNumber = item.getModelNumber();
650
		String product = "";
651
		if(StringUtils.isEmpty(modelName)){
652
			product = brand + " " + modelNumber;
653
		}else {
654
			product = brand + " " + modelName + " " + modelNumber;
655
		}
656
		return product;
657
	}
658
 
2171 rajveer 659
    /**
3929 mandeep.dh 660
     * Checks weather entity is valid or not. Entity will be invalid in one of
661
     * these cases:
2367 rajveer 662
     * <ol>
663
     * <li>The entity is not ready.
664
     * <li>The category has not been updated yet. (Set to -1).
665
     * <li>Content has not been updated after last content generation timestamp.
666
     * </ol>
667
     * 
668
     * @param entity
669
     * @return
670
     * @throws Exception
2171 rajveer 671
     */
3929 mandeep.dh 672
    private boolean isValidEntity(Entity entity) throws Exception {
2367 rajveer 673
        ExpandedEntity expEntity = new ExpandedEntity(entity);
674
        EntityState state = CreationUtils.getEntityState(entity.getID());
675
        long categoryID = expEntity.getCategoryID();
3929 mandeep.dh 676
 
677
        if (state.getStatus() != EntityStatus.READY || categoryID == -1) {
2367 rajveer 678
            return false;
679
        }
3929 mandeep.dh 680
        if (state.getMerkedReadyOn().getTime() < this.lastGenerationTime) {
2367 rajveer 681
            return false;
682
        }
683
        return true;
684
    }
685
 
3929 mandeep.dh 686
    private void populateEntityIdItemMap() {
2171 rajveer 687
        Date todate = new Date();
4775 mandeep.dh 688
        Utils.info("Processing " + items.size() + " items");
3929 mandeep.dh 689
        for (Item item : items) {
4778 mandeep.dh 690
            Utils.info(item.getId() + ":" + item.getItemStatus() + ":" + item.getCatalogItemId());
3929 mandeep.dh 691
            // TODO Can be removed as we are checking in calling function
692
            if (!(item.getItemStatus() == status.ACTIVE
693
                    || item.getItemStatus() == status.CONTENT_COMPLETE || item
5227 amit.gupta 694
                    .getItemStatus() == status.PAUSED || item.getItemStatus() == status.COMING_SOON)) {
2171 rajveer 695
                continue;
696
            }
4777 mandeep.dh 697
            Utils.info(item.getStartDate() + ":" + item.getSellingPrice());
5227 amit.gupta 698
 
699
			if (todate.getTime() < item.getStartDate()
700
					&& (!item.isSetExpectedArrivalDate() || todate.getTime() < item.getComingSoonStartDate()) 
701
					|| item.getSellingPrice() == 0) {
702
				continue;
703
			}
4777 mandeep.dh 704
            Utils.info(item.getId() + " Item is adding");
2367 rajveer 705
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
3929 mandeep.dh 706
            if (itemList == null) {
2171 rajveer 707
                itemList = new ArrayList<Item>();
5227 amit.gupta 708
            } 
2171 rajveer 709
            itemList.add(item);
710
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
711
        }
2367 rajveer 712
 
4775 mandeep.dh 713
        Utils.info("Processing " + entityIdItemMap.size() + " entities");
3929 mandeep.dh 714
        // Remove all items which have not been updated since last content
715
        // generation.
2171 rajveer 716
        List<Long> removeEntities = new ArrayList<Long>();
3929 mandeep.dh 717
        for (Long entityId : entityIdItemMap.keySet()) {
2171 rajveer 718
            boolean isValidEntity = false;
3929 mandeep.dh 719
            // If any one of the items has been updated before current
720
            // timestamp, than we generate content for whole entity
721
            for (Item item : entityIdItemMap.get(entityId)) {
5227 amit.gupta 722
                if (item.getUpdatedOn() > lastGenerationTime || item.getItemStatus()==status.COMING_SOON) {
2171 rajveer 723
                    isValidEntity = true;
724
                }
725
            }
3929 mandeep.dh 726
            if (!isValidEntity) {
2171 rajveer 727
                removeEntities.add(entityId);
728
            }
729
        }
5404 amit.gupta 730
        //Simply assign allValidEntityIds to a class variable as these need to be used where all valid entites
731
        //are needed.
732
        allValidEntityIds = new ArrayList<Long>(entityIdItemMap.keySet());
3929 mandeep.dh 733
        for (Long entityId : removeEntities) {
2171 rajveer 734
            entityIdItemMap.remove(entityId);
735
        }
4775 mandeep.dh 736
 
737
        Utils.info("Final valid entities to be processed: " + entityIdItemMap.size());
2171 rajveer 738
    }
5084 phani.kuma 739
 
740
    private void synonymTitlesExporter() {
741
    	SynonymExporter sx = new SynonymExporter();
742
        Map<Long, Map<String,List<String>>> synonyms = sx.getSynonyms();
5453 phani.kuma 743
        Map<String, List<String>> finalsynonyms = new HashMap<String, List<String>>();
5084 phani.kuma 744
    	for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
745
            long entityId = entry.getKey();
746
	    	try{
747
	            String brand = "";
5453 phani.kuma 748
	            String originalModelName = "";
749
	            String originalModelNumber = "";
5084 phani.kuma 750
	            List<String> modelNameSynonyms =  new ArrayList<String>();
751
	            List<String> modelNumberSynonyms =  new ArrayList<String>();
752
	            List<String> titles = new ArrayList<String>();
753
	            Map<String,List<String>> synonymMap = synonyms.get(entityId);
754
	            if(synonymMap != null && !synonymMap.isEmpty()){
755
	            	if(synonymMap.get("ORIGINAL_MODEL_NAME") != null && !synonymMap.get("ORIGINAL_MODEL_NAME").isEmpty()){
756
	            		modelNameSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NAME"));
5453 phani.kuma 757
	            		originalModelName = synonymMap.get("ORIGINAL_MODEL_NAME").get(0);
5084 phani.kuma 758
	            	}
759
	            	if(synonymMap.get("MODEL_NAME") != null && !synonymMap.get("MODEL_NAME").isEmpty()){
760
	            		modelNameSynonyms.addAll(synonymMap.get("MODEL_NAME"));
761
	            	}
762
	            	if(synonymMap.get("ORIGINAL_MODEL_NUMBER") != null && !synonymMap.get("ORIGINAL_MODEL_NUMBER").isEmpty()){
763
	            		modelNumberSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NUMBER"));
5453 phani.kuma 764
	            		originalModelNumber = synonymMap.get("ORIGINAL_MODEL_NUMBER").get(0);
5084 phani.kuma 765
	            	}
766
	            	if(synonymMap.get("MODEL_NUMBER") != null && !synonymMap.get("MODEL_NUMBER").isEmpty()){
767
	            		modelNumberSynonyms.addAll(synonymMap.get("MODEL_NUMBER"));
768
	            	}
769
	            	brand = ((synonymMap.get("ORIGINAL_BRAND") != null && !synonymMap.get("ORIGINAL_BRAND").isEmpty()) ? synonymMap.get("ORIGINAL_BRAND").get(0) : "");
770
	            }
771
	            for(String model_name: modelNameSynonyms){
772
	            	for(String model_number: modelNumberSynonyms){
773
	            		String title = brand + " " + model_name + " " + model_number;
774
	            		title = title.replaceAll("  ", " ");
775
	            		titles.add(title);
776
	            	}
777
	            }
5453 phani.kuma 778
	            String originaltitle = brand + " " + originalModelName + " " + originalModelNumber;
779
	            originaltitle = originaltitle.replaceAll("  ", " ");
780
	            originaltitle = originaltitle.trim();
781
	            if(!originaltitle.isEmpty()) {
782
	            	finalsynonyms.put(originaltitle, titles);
783
	            }
5084 phani.kuma 784
	        } catch (Exception e) {
785
				e.printStackTrace();
786
			}
787
    	}
788
 
789
    	String autosuggestFilename = Utils.EXPORT_JAVASCRIPT_CONTENT_PATH + "autosuggest.json";
790
        Gson gson = new Gson();
791
		try {
792
			DBUtils.store(gson.toJson(finalsynonyms), autosuggestFilename);
793
		} catch (Exception e) {
794
			e.printStackTrace();
795
		}
796
    }
2171 rajveer 797
}