Subversion Repositories SmartDukaan

Rev

Rev 6192 | Rev 6274 | 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 {
6192 amit.gupta 109
        ContentGenerationUtility cgu = new ContentGenerationUtility();
110
 
111
        // Load arguments
112
        cgu.loadArgs(args);
113
 
114
        // Call method based on arguments
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
            }
6257 rajveer 272
            ProductListGenerator.updatePriceForEntity(Long.parseLong(ENTITY_ID), items.get(0).getSellingPrice(), items.get(0).getMrp());
3929 mandeep.dh 273
        } else {
2367 rajveer 274
            items = client.getAllItemsByStatus(status.ACTIVE);
5227 amit.gupta 275
            items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
2367 rajveer 276
            items.addAll(client.getAllItemsByStatus(status.PAUSED));
3929 mandeep.dh 277
            // Clean up the data from the solr directories.
2367 rajveer 278
            removeOldResources();
279
 
280
        }
3929 mandeep.dh 281
 
282
        // this still needs to be evolved. Must not be used.
283
        if (GENERATION_TYPE.equals(GENERATION_TYPE_INCREMENTAL)) {
2367 rajveer 284
        }
285
 
3929 mandeep.dh 286
        // Populate the entityIdIemMap
287
        populateEntityIdItemMap();
2367 rajveer 288
 
289
        PriceInsertor priceInserter = new PriceInsertor();
290
 
3929 mandeep.dh 291
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
292
            long entityId = entry.getKey();
293
            List<Item> items = entry.getValue();
5664 amit.gupta 294
	            // TODO Domain name and destination directory should be read from
295
	            // properties file
296
            double minPrice = 0d;
297
            StringBuilder priceString = new StringBuilder();
298
            boolean domainOnce = true;
5669 amit.gupta 299
            boolean sourceOnce = true;
5664 amit.gupta 300
            for(String domainPath : DOMAINPATHS){
301
            	String domainName = domainPath;
302
            	String pathName = domainPath.split("\\.")[0].split(":")[0];
303
            	minPrice = priceInserter.insertPriceInHtml(items, entityId,
304
            			domainName, Utils.EXPORT_PATH + "html/entities-" +  pathName + "/", null);
305
            	if(domainOnce){
306
            		priceString.append(
307
            				"<field name=\"F_50002\">" + minPrice + "</field>");
308
            		domainOnce = false;
309
            	}
310
            	if(sources != null){
311
            		for (Source source : sources) {
312
                        minPrice = priceInserter.insertPriceInHtml(items, entityId,
313
                                domainName, Utils.EXPORT_PATH + "html/entities-" + pathName + "/",
314
                                source);
315
                        if(sourceOnce){
316
                        	priceString.append("<field name=\"F_50002_"
317
                                + source.getId() + "\">" + minPrice + "</field>");
318
                        }
319
            		}
5669 amit.gupta 320
            		sourceOnce = false;
5664 amit.gupta 321
            	}
2367 rajveer 322
            }
3929 mandeep.dh 323
 
324
            priceInserter.insertPriceInSolrData(entityId,
325
                    priceString.toString());
2367 rajveer 326
        }
3929 mandeep.dh 327
 
4058 rajveer 328
        priceInserter.copySolrSchemaFiles();
5084 phani.kuma 329
        synonymTitlesExporter();
3929 mandeep.dh 330
        // Generate partners and json objects for phones only
331
        if (!GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
4188 varun.gupt 332
            ProductListGenerator generator = new ProductListGenerator(entityIdItemMap);
6025 amit.gupta 333
            generator.generateThinkDigitFeed();
3929 mandeep.dh 334
            generator.generateProductsListXML();
5355 varun.gupt 335
            generator.generateAccessoriesXML();
5939 amit.gupta 336
            generator.generateCamerasXML();
3929 mandeep.dh 337
            generator.generateProductListJavascript();
4534 varun.gupt 338
 
339
            try	{
340
            	generator.generateProductXMLForDisplayAds();
341
            } catch (Exception e) {
342
 
343
			}
344
 
3929 mandeep.dh 345
        }
2367 rajveer 346
    }
347
 
3929 mandeep.dh 348
    /**
2171 rajveer 349
     * Generates content for the specified entity embedding links to the
350
     * specified domain name.
351
     * 
3929 mandeep.dh 352
     * The method will not generate content if one of the following conditions
353
     * is met:
2171 rajveer 354
     * <ol>
355
     * <li>The entity is not ready.
356
     * <li>The category has not been updated yet. (Set to -1).
2367 rajveer 357
     * <li>The content has not been updated.
2171 rajveer 358
     * </ol>
3929 mandeep.dh 359
     * 
2367 rajveer 360
     * @throws
2171 rajveer 361
     */
3929 mandeep.dh 362
    private void generateContent() throws Exception {
363
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL)) {
364
            entities = CreationUtils.getEntities();
2367 rajveer 365
            lastGenerationTime = new Long(0);
3929 mandeep.dh 366
        } else if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
367
            entities = new HashMap<Long, Entity>();
368
            entities.put(Long.parseLong(ENTITY_ID),
369
                    CreationUtils.getEntity(Long.parseLong(ENTITY_ID)));
370
            lastGenerationTime = new Long(0);
371
        } else {
4098 anupam.sin 372
        	entities = CreationUtils.getEntities();
373
            //  When we read lastGenerationTime from database
374
            //  then only we should mark the 
375
            //	current time as newLastGenerationTime
376
            if(timeStamp == null) {
377
            	newLastGenerationTime = new Date().getTime();
378
            	lastGenerationTime = CreationUtils.getLastContentGenerationTime();
379
            } else {
380
            	lastGenerationTime = timeStamp.getTime();
381
            }
382
 
3929 mandeep.dh 383
            log.info("lastGenerationTime: " + lastGenerationTime);
384
            if (lastGenerationTime == null) {
2171 rajveer 385
                lastGenerationTime = new Long(0);
3929 mandeep.dh 386
            }
4098 anupam.sin 387
        } 
3929 mandeep.dh 388
 
389
        // Filter invalid entities here
2367 rajveer 390
        List<Entity> validEntities = new ArrayList<Entity>();
3929 mandeep.dh 391
        for (long entityID : entities.keySet()) {
392
            if (isValidEntity(entities.get(entityID))) {
393
                validEntities.add(entities.get(entityID));
394
            }
2171 rajveer 395
        }
3929 mandeep.dh 396
 
397
        // Calculate comparison scores
398
        log.info("Calculating comparison scores");
2367 rajveer 399
        NewCMP cmp = new NewCMP(validEntities);
2171 rajveer 400
        Map<Long, Map<Long, Double>> slideScoresByEntity = cmp.getSlideScores();
2367 rajveer 401
        CreationUtils.storeSlideScores(slideScoresByEntity);
2658 rajveer 402
 
3516 rajveer 403
        // Fetch comparison statistics everyday and store them in BDB
3929 mandeep.dh 404
        log.info("Fetching comparison statistics");
3516 rajveer 405
        ComparisonStatsFetcher csf = new ComparisonStatsFetcher();
406
        csf.fetchAndStoreComparisonStats();
3929 mandeep.dh 407
 
408
        // Upload catalog to Google App Engine.
409
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL)) {
410
            log.info("Uploading Catalog to Google app engine");
3083 vikas 411
            List<Item> allItems = client.getAllItems(false);
412
            allItems.addAll(client.getAllItems(true));
413
            CatalogUploderToGAE catalogUploaderToGAE = new CatalogUploderToGAE();
414
            catalogUploaderToGAE.uploadItems(allItems);
415
        }
3929 mandeep.dh 416
 
2726 rajveer 417
        items = client.getAllItemsByStatus(status.ACTIVE);
418
        items.addAll(client.getAllItemsByStatus(status.PAUSED));
419
        items.addAll(client.getAllItemsByStatus(status.CONTENT_COMPLETE));
5227 amit.gupta 420
        items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
2726 rajveer 421
        populateEntityIdItemMap();
3929 mandeep.dh 422
 
4677 rajveer 423
        //FIXME Avoiding the finding of accesories, as list of categories for which we need to find accessories is hardocoded in code. 
424
        // We need to make that configurable. Also creating ticket to improve it.
5106 rajveer 425
        try{
426
	        log.info("Finding accessories");
5404 amit.gupta 427
	        AccessoriesFinder af = new AccessoriesFinder(new HashSet<Long>(allValidEntityIds));
5106 rajveer 428
	        Map<Long, Map<Long, List<Long>>> relatedAccessories = af.findAccessories();
429
	        CreationUtils.storeRelatedAccessories(relatedAccessories);
430
        }catch (Exception e) {
431
        	log.error("Error while generating accessories" + e);
432
		}
4677 rajveer 433
 
3929 mandeep.dh 434
        log.info("Writing JSON file for special pages");
2838 mandeep.dh 435
        SpecialPageJSONConvertor bjc = new SpecialPageJSONConvertor();
3929 mandeep.dh 436
        bjc.writeToJSONFile(new File(Utils.EXPORT_JAVASCRIPT_CONTENT_PATH
437
                + "special-pages.json"));
2838 mandeep.dh 438
 
3929 mandeep.dh 439
        log.info("Generating velocity templates, images, documents etc.");
2171 rajveer 440
        NewVUI vui = new NewVUI(lastGenerationTime);
3929 mandeep.dh 441
        for (Entity entity : validEntities) {
442
            log.info("Processing Entityid: " + entity.getID());
443
            vui.generateContentForOneEntity(entity, Utils.EXPORT_VELOCITY_PATH);
2171 rajveer 444
        }
3929 mandeep.dh 445
 
446
        // Generate synonyms list. This will be used in PriceComparisonTool to
447
        // resolve the product names.
448
        log.info("Generating synonyms");
5084 phani.kuma 449
        SynonymExporter sx = new SynonymExporter();
450
        sx.storeSynonyms(validEntities);
5004 varun.gupt 451
 
5155 varun.gupt 452
        List<Entity> allValidEntities;
453
 
454
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL))	{
455
        	allValidEntities = validEntities;
456
 
457
        } else	{
458
        	allValidEntities = new ArrayList<Entity>();
5404 amit.gupta 459
			for (Long entityId : allValidEntityIds)	{
460
				allValidEntities.add(CreationUtils.getEntity(entityId));
5155 varun.gupt 461
			}
462
        }
463
 
5004 varun.gupt 464
        log.info("Generating HTML for Site Index");
5155 varun.gupt 465
        ProductIndexGenerator indexGenerator = new ProductIndexGenerator(allValidEntities);
5004 varun.gupt 466
        indexGenerator.generate();
5642 amit.gupta 467
 
468
        log.info("Generating HTML for Site for Product Documents");
469
        ProductDocumentsGenerator asGenerator = new ProductDocumentsGenerator(allValidEntities);
470
        asGenerator.generate();
5004 varun.gupt 471
 
5117 varun.gupt 472
        log.info("Generating HTML for Accessories Compatibility Index");
5155 varun.gupt 473
        CompatibleAccessoriesIndexGenerator generator = new CompatibleAccessoriesIndexGenerator(allValidEntities);
5117 varun.gupt 474
        generator.generate();
5600 amit.gupta 475
 
5604 amit.gupta 476
        log.info("Generating HTML for Most Frequently searched keywords");
5600 amit.gupta 477
        MostFrequentlySearchedKeywords mfsk = new MostFrequentlySearchedKeywords();
5604 amit.gupta 478
        mfsk.generate();
5117 varun.gupt 479
 
5315 varun.gupt 480
        log.info("Generating HTML for Most Compared Index");
5425 amit.gupta 481
        MostComparedIndexGenerator mostCompGenerator = new MostComparedIndexGenerator(allValidEntityIds);
5315 varun.gupt 482
        mostCompGenerator.generate();
5522 varun.gupt 483
 
484
        log.info("Generating XML for Mobile Site XML feed");
485
        MobileSiteDataXMLGenerator mSiteXMLGenerator = new MobileSiteDataXMLGenerator(allValidEntities);
486
        mSiteXMLGenerator.generate();
5315 varun.gupt 487
 
3929 mandeep.dh 488
        if (newLastGenerationTime != 0) {
489
            CreationUtils.storeLastContentGenerationTime(newLastGenerationTime);
490
        }
491
 
492
 
493
        log.info("Generating Solr files");
2367 rajveer 494
        NewIR ir = new NewIR(validEntities);
2227 rajveer 495
        ir.exportIRData();
3929 mandeep.dh 496
        // ir.transformIrDataXMLtoSolrXML();
2227 rajveer 497
        ir.exportIRMetaData();
4057 rajveer 498
        ir.transformIrMetaDataXMLtoSolrSchemaXML();
499
        ir.transformIrMetaDataXMLtoSolrCatchAllXML();
2227 rajveer 500
 
3929 mandeep.dh 501
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
502
            List<Item> items = entry.getValue();
503
            for (Item item : items) {
5227 amit.gupta 504
                if (item.getItemStatus() == status.CONTENT_COMPLETE || item.getItemStatus() == status.COMING_SOON) {
5360 amit.gupta 505
                	if(item.getStartDate() <= new Date().getTime() + ONE_DAY){
5227 amit.gupta 506
                		item.setItemStatus(status.ACTIVE);
507
                		item.setStatus_description("This item is active");
508
                	} else {
509
                		item.setItemStatus(status.COMING_SOON);
510
                		String productName = getProductName(item);
511
                		String statusDescription = productName + " is coming soon.";
512
                		if(item.getExpectedArrivalDate()>new Date().getTime() + ONE_DAY){
513
                			statusDescription = productName + " will be available by " 
514
                			+ new SimpleDateFormat("dd/MM/yy").format(new Date(item.getExpectedArrivalDate()));
515
                		}
5279 amit.gupta 516
                		//Send alert to Category team one day before expected arrival date
517
                		//So they may change the expected arrival date if they want to.
518
                		if(item.getExpectedArrivalDate() < new Date().getTime() + 2*ONE_DAY && 
519
                				item.getExpectedArrivalDate() > new Date().getTime() + ONE_DAY) {
520
                				alertItems.add(item);
521
                		}
5227 amit.gupta 522
                		item.setStatus_description(statusDescription);
523
                	}
2493 rajveer 524
                    client.updateItem(item);
5279 amit.gupta 525
            	}
3929 mandeep.dh 526
            }
2493 rajveer 527
        }
5279 amit.gupta 528
        sendAlertToCategoryTeam(alertItems);
4472 mandeep.dh 529
        try {
530
            //generate products list that is to be uploaded in Amazon.
5901 amit.gupta 531
        	AmazonSCDataGenerator ascdGenerator = new AmazonSCDataGenerator(validEntities, GENERATION_TYPE);
532
            ascdGenerator.generateSCProdData();
4472 mandeep.dh 533
        } catch (Exception e) {
4994 amit.gupta 534
        	e.printStackTrace();
4640 mandeep.dh 535
            log.info("Could not generate Amazon data", e);
4472 mandeep.dh 536
        }
2171 rajveer 537
    }
2367 rajveer 538
 
5279 amit.gupta 539
    private void sendAlertToCategoryTeam(List<Item> items) {
540
    	if(items!=null && items.size()!=0){
541
			GmailUtils util = new GmailUtils();
5280 amit.gupta 542
			String[] recipients = {"amit.gupta@shop2020.in", "chaitnaya.vats@shop2020.in", "ashutosh.saxena@shop2020.in"};
5279 amit.gupta 543
			String from = "build@shop2020.in";
544
			String password = "cafe@nes";
545
			String subject = Utils.EXPECTED_ARRIVAL_ACHIEVED_TEMPLATE;
546
			StringBuffer message = new StringBuffer("Please check the following items:\n");
547
			List<File> emptyList = new ArrayList<File>();
548
			for( Item item : items){
549
				message.append("\t" + getProductName(item));
550
			}
551
			try {
552
				util.sendSSLMessage(recipients, subject, message.toString(), from, password, emptyList);
553
			} catch (Exception e){
554
				log.info("Could not send alert" + e);
555
			}
556
    	}
557
	}
558
 
559
	private String getProductName(Item item) {
5227 amit.gupta 560
    	String brand = item.getBrand();
561
		String modelName = item.getModelName();
562
		String modelNumber = item.getModelNumber();
563
		String product = "";
564
		if(StringUtils.isEmpty(modelName)){
565
			product = brand + " " + modelNumber;
566
		}else {
567
			product = brand + " " + modelName + " " + modelNumber;
568
		}
569
		return product;
570
	}
571
 
2171 rajveer 572
    /**
3929 mandeep.dh 573
     * Checks weather entity is valid or not. Entity will be invalid in one of
574
     * these cases:
2367 rajveer 575
     * <ol>
576
     * <li>The entity is not ready.
577
     * <li>The category has not been updated yet. (Set to -1).
578
     * <li>Content has not been updated after last content generation timestamp.
579
     * </ol>
580
     * 
581
     * @param entity
582
     * @return
583
     * @throws Exception
2171 rajveer 584
     */
3929 mandeep.dh 585
    private boolean isValidEntity(Entity entity) throws Exception {
2367 rajveer 586
        ExpandedEntity expEntity = new ExpandedEntity(entity);
587
        EntityState state = CreationUtils.getEntityState(entity.getID());
588
        long categoryID = expEntity.getCategoryID();
3929 mandeep.dh 589
 
590
        if (state.getStatus() != EntityStatus.READY || categoryID == -1) {
2367 rajveer 591
            return false;
592
        }
3929 mandeep.dh 593
        if (state.getMerkedReadyOn().getTime() < this.lastGenerationTime) {
2367 rajveer 594
            return false;
595
        }
596
        return true;
597
    }
598
 
3929 mandeep.dh 599
    private void populateEntityIdItemMap() {
2171 rajveer 600
        Date todate = new Date();
4775 mandeep.dh 601
        Utils.info("Processing " + items.size() + " items");
3929 mandeep.dh 602
        for (Item item : items) {
4778 mandeep.dh 603
            Utils.info(item.getId() + ":" + item.getItemStatus() + ":" + item.getCatalogItemId());
3929 mandeep.dh 604
            // TODO Can be removed as we are checking in calling function
605
            if (!(item.getItemStatus() == status.ACTIVE
606
                    || item.getItemStatus() == status.CONTENT_COMPLETE || item
5227 amit.gupta 607
                    .getItemStatus() == status.PAUSED || item.getItemStatus() == status.COMING_SOON)) {
2171 rajveer 608
                continue;
609
            }
4777 mandeep.dh 610
            Utils.info(item.getStartDate() + ":" + item.getSellingPrice());
5227 amit.gupta 611
 
612
			if (todate.getTime() < item.getStartDate()
613
					&& (!item.isSetExpectedArrivalDate() || todate.getTime() < item.getComingSoonStartDate()) 
614
					|| item.getSellingPrice() == 0) {
615
				continue;
616
			}
4777 mandeep.dh 617
            Utils.info(item.getId() + " Item is adding");
2367 rajveer 618
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
3929 mandeep.dh 619
            if (itemList == null) {
2171 rajveer 620
                itemList = new ArrayList<Item>();
5227 amit.gupta 621
            } 
2171 rajveer 622
            itemList.add(item);
623
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
624
        }
2367 rajveer 625
 
4775 mandeep.dh 626
        Utils.info("Processing " + entityIdItemMap.size() + " entities");
3929 mandeep.dh 627
        // Remove all items which have not been updated since last content
628
        // generation.
2171 rajveer 629
        List<Long> removeEntities = new ArrayList<Long>();
3929 mandeep.dh 630
        for (Long entityId : entityIdItemMap.keySet()) {
2171 rajveer 631
            boolean isValidEntity = false;
3929 mandeep.dh 632
            // If any one of the items has been updated before current
633
            // timestamp, than we generate content for whole entity
634
            for (Item item : entityIdItemMap.get(entityId)) {
5227 amit.gupta 635
                if (item.getUpdatedOn() > lastGenerationTime || item.getItemStatus()==status.COMING_SOON) {
2171 rajveer 636
                    isValidEntity = true;
637
                }
638
            }
3929 mandeep.dh 639
            if (!isValidEntity) {
2171 rajveer 640
                removeEntities.add(entityId);
641
            }
642
        }
5404 amit.gupta 643
        //Simply assign allValidEntityIds to a class variable as these need to be used where all valid entites
644
        //are needed.
645
        allValidEntityIds = new ArrayList<Long>(entityIdItemMap.keySet());
3929 mandeep.dh 646
        for (Long entityId : removeEntities) {
2171 rajveer 647
            entityIdItemMap.remove(entityId);
648
        }
4775 mandeep.dh 649
 
650
        Utils.info("Final valid entities to be processed: " + entityIdItemMap.size());
2171 rajveer 651
    }
5084 phani.kuma 652
 
653
    private void synonymTitlesExporter() {
654
    	SynonymExporter sx = new SynonymExporter();
655
        Map<Long, Map<String,List<String>>> synonyms = sx.getSynonyms();
5453 phani.kuma 656
        Map<String, List<String>> finalsynonyms = new HashMap<String, List<String>>();
5084 phani.kuma 657
    	for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
658
            long entityId = entry.getKey();
659
	    	try{
660
	            String brand = "";
5453 phani.kuma 661
	            String originalModelName = "";
662
	            String originalModelNumber = "";
5084 phani.kuma 663
	            List<String> modelNameSynonyms =  new ArrayList<String>();
664
	            List<String> modelNumberSynonyms =  new ArrayList<String>();
665
	            List<String> titles = new ArrayList<String>();
666
	            Map<String,List<String>> synonymMap = synonyms.get(entityId);
667
	            if(synonymMap != null && !synonymMap.isEmpty()){
668
	            	if(synonymMap.get("ORIGINAL_MODEL_NAME") != null && !synonymMap.get("ORIGINAL_MODEL_NAME").isEmpty()){
669
	            		modelNameSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NAME"));
5453 phani.kuma 670
	            		originalModelName = synonymMap.get("ORIGINAL_MODEL_NAME").get(0);
5084 phani.kuma 671
	            	}
672
	            	if(synonymMap.get("MODEL_NAME") != null && !synonymMap.get("MODEL_NAME").isEmpty()){
673
	            		modelNameSynonyms.addAll(synonymMap.get("MODEL_NAME"));
674
	            	}
675
	            	if(synonymMap.get("ORIGINAL_MODEL_NUMBER") != null && !synonymMap.get("ORIGINAL_MODEL_NUMBER").isEmpty()){
676
	            		modelNumberSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NUMBER"));
5453 phani.kuma 677
	            		originalModelNumber = synonymMap.get("ORIGINAL_MODEL_NUMBER").get(0);
5084 phani.kuma 678
	            	}
679
	            	if(synonymMap.get("MODEL_NUMBER") != null && !synonymMap.get("MODEL_NUMBER").isEmpty()){
680
	            		modelNumberSynonyms.addAll(synonymMap.get("MODEL_NUMBER"));
681
	            	}
682
	            	brand = ((synonymMap.get("ORIGINAL_BRAND") != null && !synonymMap.get("ORIGINAL_BRAND").isEmpty()) ? synonymMap.get("ORIGINAL_BRAND").get(0) : "");
683
	            }
684
	            for(String model_name: modelNameSynonyms){
685
	            	for(String model_number: modelNumberSynonyms){
686
	            		String title = brand + " " + model_name + " " + model_number;
687
	            		title = title.replaceAll("  ", " ");
688
	            		titles.add(title);
689
	            	}
690
	            }
5453 phani.kuma 691
	            String originaltitle = brand + " " + originalModelName + " " + originalModelNumber;
692
	            originaltitle = originaltitle.replaceAll("  ", " ");
693
	            originaltitle = originaltitle.trim();
694
	            if(!originaltitle.isEmpty()) {
695
	            	finalsynonyms.put(originaltitle, titles);
696
	            }
5084 phani.kuma 697
	        } catch (Exception e) {
698
				e.printStackTrace();
699
			}
700
    	}
701
 
702
    	String autosuggestFilename = Utils.EXPORT_JAVASCRIPT_CONTENT_PATH + "autosuggest.json";
703
        Gson gson = new Gson();
704
		try {
705
			DBUtils.store(gson.toJson(finalsynonyms), autosuggestFilename);
706
		} catch (Exception e) {
707
			e.printStackTrace();
708
		}
709
    }
2171 rajveer 710
}