Subversion Repositories SmartDukaan

Rev

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