Subversion Repositories SmartDukaan

Rev

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