Subversion Repositories SmartDukaan

Rev

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