Subversion Repositories SmartDukaan

Rev

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