Subversion Repositories SmartDukaan

Rev

Rev 5600 | Rev 5604 | 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;
8
import in.shop2020.model.v1.catalog.InventoryService.Client;
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";
71
 
4098 anupam.sin 72
    private Date 				  timeStamp			  		  = null;
3929 mandeep.dh 73
    private CommandLine           cmd                         = null;
74
    private Map<Long, List<Item>> entityIdItemMap             = new LinkedHashMap<Long, List<Item>>();
5404 amit.gupta 75
    private List<Long> 			  allValidEntityIds 			  = null;
3929 mandeep.dh 76
    private Long                  lastGenerationTime          = 0l;
77
    private Map<Long, Entity>     entities;
78
    private List<Item>            items;
79
    private List<Source>          sources;
80
    private CatalogClient         csc;
81
    private Client                client;
5279 amit.gupta 82
    private List<Item>			  alertItems;	
3929 mandeep.dh 83
    private long                  newLastGenerationTime;
84
 
85
    static {
2171 rajveer 86
        options = new Options();
87
        options.addOption(GENERATION_TYPE_OPTION, true, "Generation type");
3929 mandeep.dh 88
        options.addOption(UPDATE_TYPE_OPTION, true, "Default is : "
89
                + UPDATE_TYPE);
90
        options.addOption(ENTITY_ID_OPTION, true, "all entities " + ENTITY_ID
91
                + " by default");
4098 anupam.sin 92
        options.addOption(TIMESTAMP_OPTION, true, "Manual timestamp");
93
 
2171 rajveer 94
    }
3929 mandeep.dh 95
 
96
    public ContentGenerationUtility() throws Exception {
3127 rajveer 97
        csc = new CatalogClient();
2171 rajveer 98
        client = csc.getClient();
3573 rajveer 99
        sources = client.getAllSources();
5279 amit.gupta 100
        alertItems = new ArrayList<Item>();	
2171 rajveer 101
    }
2367 rajveer 102
 
2171 rajveer 103
    /**
104
     * @param args
3929 mandeep.dh 105
     * @throws Exception
2171 rajveer 106
     */
3929 mandeep.dh 107
    public static void main(String[] args) throws Exception {
2171 rajveer 108
        ContentGenerationUtility cgu = new ContentGenerationUtility();
3929 mandeep.dh 109
 
110
        // Load arguments
2171 rajveer 111
        cgu.loadArgs(args);
3929 mandeep.dh 112
 
113
        // Call method based on arguments
2367 rajveer 114
        cgu.callMethod();
2171 rajveer 115
    }
2367 rajveer 116
 
3929 mandeep.dh 117
    /**
118
     * Validate and set command line arguments. Exit after printing usage if
119
     * anything is astray
120
     * 
121
     * @param args
122
     *            String[] args as featured in public static void main()
2171 rajveer 123
     */
3929 mandeep.dh 124
    private void loadArgs(String[] args) {
2171 rajveer 125
        CommandLineParser parser = new PosixParser();
3929 mandeep.dh 126
 
2171 rajveer 127
        try {
128
            cmd = parser.parse(options, args);
129
        } catch (ParseException e) {
3929 mandeep.dh 130
            log.error("Error parsing arguments", e);
2171 rajveer 131
            System.exit(1);
132
        }
3929 mandeep.dh 133
 
2171 rajveer 134
        // Check for mandatory args
3929 mandeep.dh 135
        if (!(cmd.hasOption(GENERATION_TYPE_OPTION) && cmd
136
                .hasOption(UPDATE_TYPE_OPTION))) {
2171 rajveer 137
            HelpFormatter formatter = new HelpFormatter();
3929 mandeep.dh 138
            formatter.printHelp(COMMAND_LINE, options);
2171 rajveer 139
            System.exit(1);
140
        }
4098 anupam.sin 141
 
142
 
2171 rajveer 143
        GENERATION_TYPE = cmd.getOptionValue(GENERATION_TYPE_OPTION);
4098 anupam.sin 144
 
2367 rajveer 145
        UPDATE_TYPE = cmd.getOptionValue(UPDATE_TYPE_OPTION);
3929 mandeep.dh 146
 
2171 rajveer 147
        // Look for optional args.
3929 mandeep.dh 148
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
149
            if (cmd.hasOption(ENTITY_ID_OPTION)) {
2171 rajveer 150
                ENTITY_ID = cmd.getOptionValue(ENTITY_ID_OPTION);
3929 mandeep.dh 151
            } else {
2171 rajveer 152
                HelpFormatter formatter = new HelpFormatter();
3929 mandeep.dh 153
                formatter.printHelp(COMMAND_LINE, options);
2171 rajveer 154
                System.exit(1);
155
            }
156
        }
4098 anupam.sin 157
 
158
        if (GENERATION_TYPE_INCREMENTAL.equals(GENERATION_TYPE))
159
        	if (cmd.hasOption(TIMESTAMP_OPTION)) {
160
        		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
161
        		try {
162
        		    timeStamp = df.parse(cmd.getOptionValue(TIMESTAMP_OPTION));
163
        		} catch(Exception e) {
164
        			HelpFormatter formatter = new HelpFormatter();
165
                    formatter.printHelp(COMMAND_LINE, options);
166
                    System.exit(1);
167
        		}
168
        	}
2367 rajveer 169
    }
3929 mandeep.dh 170
 
2367 rajveer 171
    /**
172
     * Call method based on arguments
3929 mandeep.dh 173
     * 
2367 rajveer 174
     * @throws Exception
175
     */
3929 mandeep.dh 176
    private void callMethod() {
177
        boolean isSuccess = false;
178
        String logfile = "/tmp/content-from-cms.log";
179
        if (UPDATE_TYPE.equals(UPDATE_TYPE_CONTENT)) {
180
            logfile = "/tmp/content-from-cms.log";
181
            try {
182
                this.generateContent();
183
                isSuccess = true;
184
            } catch (Exception e) {
185
                log.error("Error generating content", e);
186
            }
187
        }
188
 
189
        if (UPDATE_TYPE.equals(UPDATE_TYPE_CATALOG)) {
190
            logfile = "/tmp/content-from-catalog.log";
191
            try {
192
                this.updatePrices();
193
                isSuccess = true;
194
            } catch (Exception e) {
195
                log.error("Error updating prices", e);
196
            }
197
        }
198
 
4969 amit.gupta 199
        GmailUtils gm = new GmailUtils();
5058 amit.gupta 200
        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 201
 
202
        try {
203
            gm.sendSSLMessage(sendTo, "Content Generation Successful ? : "
204
                    + isSuccess, "Content generation completed at time : "
205
                    + Calendar.getInstance().getTime().toString(),
4311 rajveer 206
                    "build@shop2020.in", "cafe@nes", logfile);
4099 anupam.sin 207
        } catch (MessagingException e) {
208
            log.error("Could not send status mail", e);
4969 amit.gupta 209
        }
2367 rajveer 210
    }
211
 
3929 mandeep.dh 212
    public boolean cleanDir(File dir, boolean deleteSelf) {
213
        if (dir.isDirectory()) {
214
            String[] children = dir.list();
215
            for (int i = 0; i < children.length; i++) {
216
                boolean success = cleanDir(new File(dir, children[i]), true);
217
                if (!success) {
218
                    return false;
219
                }
220
            }
221
        }
222
 
223
        // The directory is now empty so delete it
224
        if (deleteSelf) {
225
            return dir.delete();
226
        }
227
 
228
        return true;
229
    }
230
 
231
    private void removeOldResources() throws IOException {
232
        File f = new File(Utils.EXPORT_SOLR_PATH);
233
        if (f.exists()) {
234
            cleanDir(f, false);
235
        }
236
 
237
        File f1 = new File(Utils.EXPORT_ENTITIES_PATH_LOCALHOST);
238
        if (f1.exists()) {
239
            cleanDir(f1, false);
240
        }
241
 
242
        File f2 = new File(Utils.EXPORT_ENTITIES_PATH_SAHOLIC);
243
        if (f2.exists()) {
244
            cleanDir(f2, false);
245
        }
246
 
247
        File f3 = new File(Utils.EXPORT_ENTITIES_PATH_SHOP2020);
248
        if (f3.exists()) {
249
            cleanDir(f3, false);
250
        }
251
    }
252
 
2367 rajveer 253
    /**
254
     * Update the prices in the generated content
3929 mandeep.dh 255
     * 
2367 rajveer 256
     * @throws Exception
257
     */
258
    private void updatePrices() throws Exception {
3929 mandeep.dh 259
        lastGenerationTime = new Long(0);
260
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
2367 rajveer 261
            items = client.getItemsByCatalogId(Long.parseLong(ENTITY_ID));
5479 amit.gupta 262
            Iterator<Item> it = items.iterator();
263
            while(it.hasNext()){
264
            	status st = it.next().getItemStatus();
265
            	if(!(st.equals(status.ACTIVE) || st.equals(status.PAUSED) || 
266
            				st.equals(status.COMING_SOON) || st.equals(status.PHASED_OUT))){
267
            		it.remove();
268
            	}
269
            }
270
            try {
271
            	//Generate prices and availability data for amazon
272
            	AmazonSCDataGenerator.generatePricesAndAvailability(items);
273
            } catch (Exception e) {
274
            	log.info("Could not generate Amazon prices and availability", e);
275
            }
3929 mandeep.dh 276
        } else {
2367 rajveer 277
            items = client.getAllItemsByStatus(status.ACTIVE);
5227 amit.gupta 278
            items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
2367 rajveer 279
            items.addAll(client.getAllItemsByStatus(status.PAUSED));
3929 mandeep.dh 280
            // Clean up the data from the solr directories.
2367 rajveer 281
            removeOldResources();
282
 
283
        }
3929 mandeep.dh 284
 
285
        // this still needs to be evolved. Must not be used.
286
        if (GENERATION_TYPE.equals(GENERATION_TYPE_INCREMENTAL)) {
2367 rajveer 287
        }
288
 
3929 mandeep.dh 289
        // Populate the entityIdIemMap
290
        populateEntityIdItemMap();
2367 rajveer 291
 
292
        PriceInsertor priceInserter = new PriceInsertor();
293
 
3929 mandeep.dh 294
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
295
            long entityId = entry.getKey();
296
            List<Item> items = entry.getValue();
297
            // TODO Domain name and destination directory should be read from
298
            // properties file
299
            double minPrice = priceInserter.insertPriceInHtml(items, entityId,
300
                    "saholic.com", Utils.EXPORT_ENTITIES_PATH_SAHOLIC, null);
301
            priceInserter.insertPriceInHtml(items, entityId, "shop2020.in",
302
                    Utils.EXPORT_ENTITIES_PATH_SHOP2020, null);
303
            priceInserter.insertPriceInHtml(items, entityId, "localhost:8090",
304
                    Utils.EXPORT_ENTITIES_PATH_LOCALHOST, null);
305
            StringBuilder priceString = new StringBuilder(
306
                    "<field name=\"F_50002\">" + minPrice + "</field>");
307
 
308
            if (sources != null) {
309
                for (Source source : sources) {
310
                    minPrice = priceInserter.insertPriceInHtml(items, entityId,
311
                            "saholic.com", Utils.EXPORT_ENTITIES_PATH_SAHOLIC,
312
                            source);
313
                    priceInserter.insertPriceInHtml(items, entityId,
314
                            "shop2020.in", Utils.EXPORT_ENTITIES_PATH_SHOP2020,
315
                            source);
316
                    priceInserter.insertPriceInHtml(items, entityId,
317
                            "localhost:8090",
318
                            Utils.EXPORT_ENTITIES_PATH_LOCALHOST, source);
319
                    priceString.append("<field name=\"F_50002_"
320
                            + source.getId() + "\">" + minPrice + "</field>");
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);
3929 mandeep.dh 333
            generator.generateProductsListXML();
5355 varun.gupt 334
            generator.generateAccessoriesXML();
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();
465
 
5117 varun.gupt 466
        log.info("Generating HTML for Accessories Compatibility Index");
5155 varun.gupt 467
        CompatibleAccessoriesIndexGenerator generator = new CompatibleAccessoriesIndexGenerator(allValidEntities);
5117 varun.gupt 468
        generator.generate();
5600 amit.gupta 469
 
5601 amit.gupta 470
        /*log.info("Generating HTML for Most Frequently searched keywords");
5600 amit.gupta 471
        MostFrequentlySearchedKeywords mfsk = new MostFrequentlySearchedKeywords();
5601 amit.gupta 472
        mfsk.generate();*/
5117 varun.gupt 473
 
5315 varun.gupt 474
        log.info("Generating HTML for Most Compared Index");
5425 amit.gupta 475
        MostComparedIndexGenerator mostCompGenerator = new MostComparedIndexGenerator(allValidEntityIds);
5315 varun.gupt 476
        mostCompGenerator.generate();
5522 varun.gupt 477
 
478
        log.info("Generating XML for Mobile Site XML feed");
479
        MobileSiteDataXMLGenerator mSiteXMLGenerator = new MobileSiteDataXMLGenerator(allValidEntities);
480
        mSiteXMLGenerator.generate();
5315 varun.gupt 481
 
3929 mandeep.dh 482
        if (newLastGenerationTime != 0) {
483
            CreationUtils.storeLastContentGenerationTime(newLastGenerationTime);
484
        }
485
 
486
 
487
        log.info("Generating Solr files");
2367 rajveer 488
        NewIR ir = new NewIR(validEntities);
2227 rajveer 489
        ir.exportIRData();
3929 mandeep.dh 490
        // ir.transformIrDataXMLtoSolrXML();
2227 rajveer 491
        ir.exportIRMetaData();
4057 rajveer 492
        ir.transformIrMetaDataXMLtoSolrSchemaXML();
493
        ir.transformIrMetaDataXMLtoSolrCatchAllXML();
2227 rajveer 494
 
3929 mandeep.dh 495
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
496
            List<Item> items = entry.getValue();
497
            for (Item item : items) {
5227 amit.gupta 498
                if (item.getItemStatus() == status.CONTENT_COMPLETE || item.getItemStatus() == status.COMING_SOON) {
5360 amit.gupta 499
                	if(item.getStartDate() <= new Date().getTime() + ONE_DAY){
5227 amit.gupta 500
                		item.setItemStatus(status.ACTIVE);
501
                		item.setStatus_description("This item is active");
502
                	} else {
503
                		item.setItemStatus(status.COMING_SOON);
504
                		String productName = getProductName(item);
505
                		String statusDescription = productName + " is coming soon.";
506
                		if(item.getExpectedArrivalDate()>new Date().getTime() + ONE_DAY){
507
                			statusDescription = productName + " will be available by " 
508
                			+ new SimpleDateFormat("dd/MM/yy").format(new Date(item.getExpectedArrivalDate()));
509
                		}
5279 amit.gupta 510
                		//Send alert to Category team one day before expected arrival date
511
                		//So they may change the expected arrival date if they want to.
512
                		if(item.getExpectedArrivalDate() < new Date().getTime() + 2*ONE_DAY && 
513
                				item.getExpectedArrivalDate() > new Date().getTime() + ONE_DAY) {
514
                				alertItems.add(item);
515
                		}
5227 amit.gupta 516
                		item.setStatus_description(statusDescription);
517
                	}
2493 rajveer 518
                    client.updateItem(item);
5279 amit.gupta 519
            	}
3929 mandeep.dh 520
            }
2493 rajveer 521
        }
5279 amit.gupta 522
        sendAlertToCategoryTeam(alertItems);
4472 mandeep.dh 523
        try {
524
            //generate products list that is to be uploaded in Amazon.
5257 amit.gupta 525
        	AmazonSCDataGenerator ascdGenerator = new AmazonSCDataGenerator();
526
            ascdGenerator.generateSCProdData(validEntities, GENERATION_TYPE);
4472 mandeep.dh 527
        } catch (Exception e) {
4994 amit.gupta 528
        	e.printStackTrace();
4640 mandeep.dh 529
            log.info("Could not generate Amazon data", e);
4472 mandeep.dh 530
        }
2171 rajveer 531
    }
2367 rajveer 532
 
5279 amit.gupta 533
    private void sendAlertToCategoryTeam(List<Item> items) {
534
    	if(items!=null && items.size()!=0){
535
			GmailUtils util = new GmailUtils();
5280 amit.gupta 536
			String[] recipients = {"amit.gupta@shop2020.in", "chaitnaya.vats@shop2020.in", "ashutosh.saxena@shop2020.in"};
5279 amit.gupta 537
			String from = "build@shop2020.in";
538
			String password = "cafe@nes";
539
			String subject = Utils.EXPECTED_ARRIVAL_ACHIEVED_TEMPLATE;
540
			StringBuffer message = new StringBuffer("Please check the following items:\n");
541
			List<File> emptyList = new ArrayList<File>();
542
			for( Item item : items){
543
				message.append("\t" + getProductName(item));
544
			}
545
			try {
546
				util.sendSSLMessage(recipients, subject, message.toString(), from, password, emptyList);
547
			} catch (Exception e){
548
				log.info("Could not send alert" + e);
549
			}
550
    	}
551
	}
552
 
553
	private String getProductName(Item item) {
5227 amit.gupta 554
    	String brand = item.getBrand();
555
		String modelName = item.getModelName();
556
		String modelNumber = item.getModelNumber();
557
		String product = "";
558
		if(StringUtils.isEmpty(modelName)){
559
			product = brand + " " + modelNumber;
560
		}else {
561
			product = brand + " " + modelName + " " + modelNumber;
562
		}
563
		return product;
564
	}
565
 
2171 rajveer 566
    /**
3929 mandeep.dh 567
     * Checks weather entity is valid or not. Entity will be invalid in one of
568
     * these cases:
2367 rajveer 569
     * <ol>
570
     * <li>The entity is not ready.
571
     * <li>The category has not been updated yet. (Set to -1).
572
     * <li>Content has not been updated after last content generation timestamp.
573
     * </ol>
574
     * 
575
     * @param entity
576
     * @return
577
     * @throws Exception
2171 rajveer 578
     */
3929 mandeep.dh 579
    private boolean isValidEntity(Entity entity) throws Exception {
2367 rajveer 580
        ExpandedEntity expEntity = new ExpandedEntity(entity);
581
        EntityState state = CreationUtils.getEntityState(entity.getID());
582
        long categoryID = expEntity.getCategoryID();
3929 mandeep.dh 583
 
584
        if (state.getStatus() != EntityStatus.READY || categoryID == -1) {
2367 rajveer 585
            return false;
586
        }
3929 mandeep.dh 587
        if (state.getMerkedReadyOn().getTime() < this.lastGenerationTime) {
2367 rajveer 588
            return false;
589
        }
590
        return true;
591
    }
592
 
3929 mandeep.dh 593
    private void populateEntityIdItemMap() {
2171 rajveer 594
        Date todate = new Date();
4775 mandeep.dh 595
        Utils.info("Processing " + items.size() + " items");
3929 mandeep.dh 596
        for (Item item : items) {
4778 mandeep.dh 597
            Utils.info(item.getId() + ":" + item.getItemStatus() + ":" + item.getCatalogItemId());
3929 mandeep.dh 598
            // TODO Can be removed as we are checking in calling function
599
            if (!(item.getItemStatus() == status.ACTIVE
600
                    || item.getItemStatus() == status.CONTENT_COMPLETE || item
5227 amit.gupta 601
                    .getItemStatus() == status.PAUSED || item.getItemStatus() == status.COMING_SOON)) {
2171 rajveer 602
                continue;
603
            }
4777 mandeep.dh 604
            Utils.info(item.getStartDate() + ":" + item.getSellingPrice());
5227 amit.gupta 605
 
606
			if (todate.getTime() < item.getStartDate()
607
					&& (!item.isSetExpectedArrivalDate() || todate.getTime() < item.getComingSoonStartDate()) 
608
					|| item.getSellingPrice() == 0) {
609
				continue;
610
			}
4777 mandeep.dh 611
            Utils.info(item.getId() + " Item is adding");
2367 rajveer 612
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
3929 mandeep.dh 613
            if (itemList == null) {
2171 rajveer 614
                itemList = new ArrayList<Item>();
5227 amit.gupta 615
            } 
2171 rajveer 616
            itemList.add(item);
617
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
618
        }
2367 rajveer 619
 
4775 mandeep.dh 620
        Utils.info("Processing " + entityIdItemMap.size() + " entities");
3929 mandeep.dh 621
        // Remove all items which have not been updated since last content
622
        // generation.
2171 rajveer 623
        List<Long> removeEntities = new ArrayList<Long>();
3929 mandeep.dh 624
        for (Long entityId : entityIdItemMap.keySet()) {
2171 rajveer 625
            boolean isValidEntity = false;
3929 mandeep.dh 626
            // If any one of the items has been updated before current
627
            // timestamp, than we generate content for whole entity
628
            for (Item item : entityIdItemMap.get(entityId)) {
5227 amit.gupta 629
                if (item.getUpdatedOn() > lastGenerationTime || item.getItemStatus()==status.COMING_SOON) {
2171 rajveer 630
                    isValidEntity = true;
631
                }
632
            }
3929 mandeep.dh 633
            if (!isValidEntity) {
2171 rajveer 634
                removeEntities.add(entityId);
635
            }
636
        }
5404 amit.gupta 637
        //Simply assign allValidEntityIds to a class variable as these need to be used where all valid entites
638
        //are needed.
639
        allValidEntityIds = new ArrayList<Long>(entityIdItemMap.keySet());
3929 mandeep.dh 640
        for (Long entityId : removeEntities) {
2171 rajveer 641
            entityIdItemMap.remove(entityId);
642
        }
4775 mandeep.dh 643
 
644
        Utils.info("Final valid entities to be processed: " + entityIdItemMap.size());
2171 rajveer 645
    }
5084 phani.kuma 646
 
647
    private void synonymTitlesExporter() {
648
    	SynonymExporter sx = new SynonymExporter();
649
        Map<Long, Map<String,List<String>>> synonyms = sx.getSynonyms();
5453 phani.kuma 650
        Map<String, List<String>> finalsynonyms = new HashMap<String, List<String>>();
5084 phani.kuma 651
    	for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
652
            long entityId = entry.getKey();
653
	    	try{
654
	            String brand = "";
5453 phani.kuma 655
	            String originalModelName = "";
656
	            String originalModelNumber = "";
5084 phani.kuma 657
	            List<String> modelNameSynonyms =  new ArrayList<String>();
658
	            List<String> modelNumberSynonyms =  new ArrayList<String>();
659
	            List<String> titles = new ArrayList<String>();
660
	            Map<String,List<String>> synonymMap = synonyms.get(entityId);
661
	            if(synonymMap != null && !synonymMap.isEmpty()){
662
	            	if(synonymMap.get("ORIGINAL_MODEL_NAME") != null && !synonymMap.get("ORIGINAL_MODEL_NAME").isEmpty()){
663
	            		modelNameSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NAME"));
5453 phani.kuma 664
	            		originalModelName = synonymMap.get("ORIGINAL_MODEL_NAME").get(0);
5084 phani.kuma 665
	            	}
666
	            	if(synonymMap.get("MODEL_NAME") != null && !synonymMap.get("MODEL_NAME").isEmpty()){
667
	            		modelNameSynonyms.addAll(synonymMap.get("MODEL_NAME"));
668
	            	}
669
	            	if(synonymMap.get("ORIGINAL_MODEL_NUMBER") != null && !synonymMap.get("ORIGINAL_MODEL_NUMBER").isEmpty()){
670
	            		modelNumberSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NUMBER"));
5453 phani.kuma 671
	            		originalModelNumber = synonymMap.get("ORIGINAL_MODEL_NUMBER").get(0);
5084 phani.kuma 672
	            	}
673
	            	if(synonymMap.get("MODEL_NUMBER") != null && !synonymMap.get("MODEL_NUMBER").isEmpty()){
674
	            		modelNumberSynonyms.addAll(synonymMap.get("MODEL_NUMBER"));
675
	            	}
676
	            	brand = ((synonymMap.get("ORIGINAL_BRAND") != null && !synonymMap.get("ORIGINAL_BRAND").isEmpty()) ? synonymMap.get("ORIGINAL_BRAND").get(0) : "");
677
	            }
678
	            for(String model_name: modelNameSynonyms){
679
	            	for(String model_number: modelNumberSynonyms){
680
	            		String title = brand + " " + model_name + " " + model_number;
681
	            		title = title.replaceAll("  ", " ");
682
	            		titles.add(title);
683
	            	}
684
	            }
5453 phani.kuma 685
	            String originaltitle = brand + " " + originalModelName + " " + originalModelNumber;
686
	            originaltitle = originaltitle.replaceAll("  ", " ");
687
	            originaltitle = originaltitle.trim();
688
	            if(!originaltitle.isEmpty()) {
689
	            	finalsynonyms.put(originaltitle, titles);
690
	            }
5084 phani.kuma 691
	        } catch (Exception e) {
692
				e.printStackTrace();
693
			}
694
    	}
695
 
696
    	String autosuggestFilename = Utils.EXPORT_JAVASCRIPT_CONTENT_PATH + "autosuggest.json";
697
        Gson gson = new Gson();
698
		try {
699
			DBUtils.store(gson.toJson(finalsynonyms), autosuggestFilename);
700
		} catch (Exception e) {
701
			e.printStackTrace();
702
		}
703
    }
2171 rajveer 704
}