Subversion Repositories SmartDukaan

Rev

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