Subversion Repositories SmartDukaan

Rev

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