Subversion Repositories SmartDukaan

Rev

Rev 4679 | Rev 4685 | 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;
3929 mandeep.dh 39
import org.apache.commons.logging.Log;
40
import org.apache.commons.logging.LogFactory;
2171 rajveer 41
 
3929 mandeep.dh 42
public class ContentGenerationUtility {
43
    private static final String   UPDATE_TYPE_CATALOG         = "CATALOG";
2171 rajveer 44
 
3929 mandeep.dh 45
    private static final String   UPDATE_TYPE_CONTENT         = "CONTENT";
3083 vikas 46
 
4098 anupam.sin 47
    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 48
 
49
    private static Log            log                         = LogFactory
50
                                                                      .getLog(ContentGenerationUtility.class);
51
 
52
    // Commandline options
53
    private static Options        options                     = null;
54
    private static final String   GENERATION_TYPE_INCREMENTAL = "INCREMENTAL";
55
    private static final String   GENERATION_TYPE_ALL         = "ALL";
56
    private static final String   GENERATION_TYPE_ONE         = "ONE";
57
    private static final String   UPDATE_TYPE_OPTION          = "u";
58
    private static final String   GENERATION_TYPE_OPTION      = "t";
59
    private static final String   ENTITY_ID_OPTION            = "e";
4098 anupam.sin 60
    private static final String   TIMESTAMP_OPTION            = "s";
3929 mandeep.dh 61
 
62
    // Default values of cmdline options
63
    private static String         UPDATE_TYPE                 = UPDATE_TYPE_CONTENT;
64
    private static String         GENERATION_TYPE             = GENERATION_TYPE_INCREMENTAL;
65
    private static String         ENTITY_ID                   = "ALL";
66
 
4098 anupam.sin 67
    private Date 				  timeStamp			  		  = null;
3929 mandeep.dh 68
    private CommandLine           cmd                         = null;
69
    private Map<Long, List<Item>> entityIdItemMap             = new LinkedHashMap<Long, List<Item>>();
70
    private Long                  lastGenerationTime          = 0l;
71
    private Map<Long, Entity>     entities;
72
    private List<Item>            items;
73
    private List<Source>          sources;
74
    private CatalogClient         csc;
75
    private Client                client;
76
 
77
    private long                  newLastGenerationTime;
78
 
79
    static {
2171 rajveer 80
        options = new Options();
81
        options.addOption(GENERATION_TYPE_OPTION, true, "Generation type");
3929 mandeep.dh 82
        options.addOption(UPDATE_TYPE_OPTION, true, "Default is : "
83
                + UPDATE_TYPE);
84
        options.addOption(ENTITY_ID_OPTION, true, "all entities " + ENTITY_ID
85
                + " by default");
4098 anupam.sin 86
        options.addOption(TIMESTAMP_OPTION, true, "Manual timestamp");
87
 
2171 rajveer 88
    }
3929 mandeep.dh 89
 
90
    public ContentGenerationUtility() throws Exception {
3127 rajveer 91
        csc = new CatalogClient();
2171 rajveer 92
        client = csc.getClient();
3573 rajveer 93
        sources = client.getAllSources();
2171 rajveer 94
    }
2367 rajveer 95
 
2171 rajveer 96
    /**
97
     * @param args
3929 mandeep.dh 98
     * @throws Exception
2171 rajveer 99
     */
3929 mandeep.dh 100
    public static void main(String[] args) throws Exception {
2171 rajveer 101
        ContentGenerationUtility cgu = new ContentGenerationUtility();
3929 mandeep.dh 102
 
103
        // Load arguments
2171 rajveer 104
        cgu.loadArgs(args);
3929 mandeep.dh 105
 
106
        // Call method based on arguments
2367 rajveer 107
        cgu.callMethod();
2171 rajveer 108
    }
2367 rajveer 109
 
3929 mandeep.dh 110
    /**
111
     * Validate and set command line arguments. Exit after printing usage if
112
     * anything is astray
113
     * 
114
     * @param args
115
     *            String[] args as featured in public static void main()
2171 rajveer 116
     */
3929 mandeep.dh 117
    private void loadArgs(String[] args) {
2171 rajveer 118
        CommandLineParser parser = new PosixParser();
3929 mandeep.dh 119
 
2171 rajveer 120
        try {
121
            cmd = parser.parse(options, args);
122
        } catch (ParseException e) {
3929 mandeep.dh 123
            log.error("Error parsing arguments", e);
2171 rajveer 124
            System.exit(1);
125
        }
3929 mandeep.dh 126
 
2171 rajveer 127
        // Check for mandatory args
3929 mandeep.dh 128
        if (!(cmd.hasOption(GENERATION_TYPE_OPTION) && cmd
129
                .hasOption(UPDATE_TYPE_OPTION))) {
2171 rajveer 130
            HelpFormatter formatter = new HelpFormatter();
3929 mandeep.dh 131
            formatter.printHelp(COMMAND_LINE, options);
2171 rajveer 132
            System.exit(1);
133
        }
4098 anupam.sin 134
 
135
 
2171 rajveer 136
        GENERATION_TYPE = cmd.getOptionValue(GENERATION_TYPE_OPTION);
4098 anupam.sin 137
 
2367 rajveer 138
        UPDATE_TYPE = cmd.getOptionValue(UPDATE_TYPE_OPTION);
3929 mandeep.dh 139
 
2171 rajveer 140
        // Look for optional args.
3929 mandeep.dh 141
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
142
            if (cmd.hasOption(ENTITY_ID_OPTION)) {
2171 rajveer 143
                ENTITY_ID = cmd.getOptionValue(ENTITY_ID_OPTION);
3929 mandeep.dh 144
            } else {
2171 rajveer 145
                HelpFormatter formatter = new HelpFormatter();
3929 mandeep.dh 146
                formatter.printHelp(COMMAND_LINE, options);
2171 rajveer 147
                System.exit(1);
148
            }
149
        }
4098 anupam.sin 150
 
151
        if (GENERATION_TYPE_INCREMENTAL.equals(GENERATION_TYPE))
152
        	if (cmd.hasOption(TIMESTAMP_OPTION)) {
153
        		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
154
        		try {
155
        		    timeStamp = df.parse(cmd.getOptionValue(TIMESTAMP_OPTION));
156
        		} catch(Exception e) {
157
        			HelpFormatter formatter = new HelpFormatter();
158
                    formatter.printHelp(COMMAND_LINE, options);
159
                    System.exit(1);
160
        		}
161
        	}
2367 rajveer 162
    }
3929 mandeep.dh 163
 
2367 rajveer 164
    /**
165
     * Call method based on arguments
3929 mandeep.dh 166
     * 
2367 rajveer 167
     * @throws Exception
168
     */
3929 mandeep.dh 169
    private void callMethod() {
170
        boolean isSuccess = false;
171
        String logfile = "/tmp/content-from-cms.log";
172
        if (UPDATE_TYPE.equals(UPDATE_TYPE_CONTENT)) {
173
            logfile = "/tmp/content-from-cms.log";
174
            try {
175
                this.generateContent();
176
                isSuccess = true;
177
            } catch (Exception e) {
178
                log.error("Error generating content", e);
179
            }
180
        }
181
 
182
        if (UPDATE_TYPE.equals(UPDATE_TYPE_CATALOG)) {
183
            logfile = "/tmp/content-from-catalog.log";
184
            try {
185
                this.updatePrices();
186
                isSuccess = true;
187
            } catch (Exception e) {
188
                log.error("Error updating prices", e);
189
            }
190
        }
191
 
4099 anupam.sin 192
        GmailUtils gm = new GmailUtils();
4168 rajveer 193
        String[] sendTo = { "rajveer.singh@shop2020.in", "mandeep.dhir@shop2020.in" };
4099 anupam.sin 194
 
195
        try {
196
            gm.sendSSLMessage(sendTo, "Content Generation Successful ? : "
197
                    + isSuccess, "Content generation completed at time : "
198
                    + Calendar.getInstance().getTime().toString(),
4311 rajveer 199
                    "build@shop2020.in", "cafe@nes", logfile);
4099 anupam.sin 200
        } catch (MessagingException e) {
201
            log.error("Could not send status mail", e);
202
        }
2367 rajveer 203
    }
204
 
3929 mandeep.dh 205
    public boolean cleanDir(File dir, boolean deleteSelf) {
206
        if (dir.isDirectory()) {
207
            String[] children = dir.list();
208
            for (int i = 0; i < children.length; i++) {
209
                boolean success = cleanDir(new File(dir, children[i]), true);
210
                if (!success) {
211
                    return false;
212
                }
213
            }
214
        }
215
 
216
        // The directory is now empty so delete it
217
        if (deleteSelf) {
218
            return dir.delete();
219
        }
220
 
221
        return true;
222
    }
223
 
224
    private void removeOldResources() throws IOException {
225
        File f = new File(Utils.EXPORT_SOLR_PATH);
226
        if (f.exists()) {
227
            cleanDir(f, false);
228
        }
229
 
230
        File f1 = new File(Utils.EXPORT_ENTITIES_PATH_LOCALHOST);
231
        if (f1.exists()) {
232
            cleanDir(f1, false);
233
        }
234
 
235
        File f2 = new File(Utils.EXPORT_ENTITIES_PATH_SAHOLIC);
236
        if (f2.exists()) {
237
            cleanDir(f2, false);
238
        }
239
 
240
        File f3 = new File(Utils.EXPORT_ENTITIES_PATH_SHOP2020);
241
        if (f3.exists()) {
242
            cleanDir(f3, false);
243
        }
244
    }
245
 
2367 rajveer 246
    /**
247
     * Update the prices in the generated content
3929 mandeep.dh 248
     * 
2367 rajveer 249
     * @throws Exception
250
     */
251
    private void updatePrices() throws Exception {
3929 mandeep.dh 252
        lastGenerationTime = new Long(0);
253
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
2367 rajveer 254
            items = client.getItemsByCatalogId(Long.parseLong(ENTITY_ID));
3929 mandeep.dh 255
        } else {
2367 rajveer 256
            items = client.getAllItemsByStatus(status.ACTIVE);
257
            items.addAll(client.getAllItemsByStatus(status.PAUSED));
4472 mandeep.dh 258
            try {
259
                //Generate prices and availability data for amazon
260
                AmazonSCDataGenerator.generatePricesAndAvailability();
261
            } catch (Exception e) {
262
                // TODO: handle exception
263
            }
3929 mandeep.dh 264
            // Clean up the data from the solr directories.
2367 rajveer 265
            removeOldResources();
266
 
267
        }
3929 mandeep.dh 268
 
269
        // this still needs to be evolved. Must not be used.
270
        if (GENERATION_TYPE.equals(GENERATION_TYPE_INCREMENTAL)) {
2367 rajveer 271
        }
272
 
3929 mandeep.dh 273
        // Populate the entityIdIemMap
274
        populateEntityIdItemMap();
2367 rajveer 275
 
276
        PriceInsertor priceInserter = new PriceInsertor();
277
 
3929 mandeep.dh 278
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
279
            long entityId = entry.getKey();
280
            List<Item> items = entry.getValue();
281
            // TODO Domain name and destination directory should be read from
282
            // properties file
283
            double minPrice = priceInserter.insertPriceInHtml(items, entityId,
284
                    "saholic.com", Utils.EXPORT_ENTITIES_PATH_SAHOLIC, null);
285
            priceInserter.insertPriceInHtml(items, entityId, "shop2020.in",
286
                    Utils.EXPORT_ENTITIES_PATH_SHOP2020, null);
287
            priceInserter.insertPriceInHtml(items, entityId, "localhost:8090",
288
                    Utils.EXPORT_ENTITIES_PATH_LOCALHOST, null);
289
            StringBuilder priceString = new StringBuilder(
290
                    "<field name=\"F_50002\">" + minPrice + "</field>");
291
 
292
            if (sources != null) {
293
                for (Source source : sources) {
294
                    minPrice = priceInserter.insertPriceInHtml(items, entityId,
295
                            "saholic.com", Utils.EXPORT_ENTITIES_PATH_SAHOLIC,
296
                            source);
297
                    priceInserter.insertPriceInHtml(items, entityId,
298
                            "shop2020.in", Utils.EXPORT_ENTITIES_PATH_SHOP2020,
299
                            source);
300
                    priceInserter.insertPriceInHtml(items, entityId,
301
                            "localhost:8090",
302
                            Utils.EXPORT_ENTITIES_PATH_LOCALHOST, source);
303
                    priceString.append("<field name=\"F_50002_"
304
                            + source.getId() + "\">" + minPrice + "</field>");
305
                }
2367 rajveer 306
            }
3929 mandeep.dh 307
 
308
            priceInserter.insertPriceInSolrData(entityId,
309
                    priceString.toString());
2367 rajveer 310
        }
3929 mandeep.dh 311
 
4058 rajveer 312
        priceInserter.copySolrSchemaFiles();
313
 
3929 mandeep.dh 314
        // Generate partners and json objects for phones only
315
        if (!GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
4188 varun.gupt 316
            ProductListGenerator generator = new ProductListGenerator(entityIdItemMap);
3929 mandeep.dh 317
            generator.generateProductsListXML();
318
            generator.generateProductListJavascript();
4534 varun.gupt 319
 
320
 
321
            try	{
322
            	generator.generateProductXMLForDisplayAds();
323
            } catch (Exception e) {
324
 
325
			}
326
 
3929 mandeep.dh 327
        }
2367 rajveer 328
    }
329
 
3929 mandeep.dh 330
    /**
2171 rajveer 331
     * Generates content for the specified entity embedding links to the
332
     * specified domain name.
333
     * 
3929 mandeep.dh 334
     * The method will not generate content if one of the following conditions
335
     * is met:
2171 rajveer 336
     * <ol>
337
     * <li>The entity is not ready.
338
     * <li>The category has not been updated yet. (Set to -1).
2367 rajveer 339
     * <li>The content has not been updated.
2171 rajveer 340
     * </ol>
3929 mandeep.dh 341
     * 
2367 rajveer 342
     * @throws
2171 rajveer 343
     */
3929 mandeep.dh 344
    private void generateContent() throws Exception {
345
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL)) {
346
            entities = CreationUtils.getEntities();
2367 rajveer 347
            lastGenerationTime = new Long(0);
3929 mandeep.dh 348
        } else if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
349
            entities = new HashMap<Long, Entity>();
350
            entities.put(Long.parseLong(ENTITY_ID),
351
                    CreationUtils.getEntity(Long.parseLong(ENTITY_ID)));
352
            lastGenerationTime = new Long(0);
353
        } else {
4098 anupam.sin 354
        	entities = CreationUtils.getEntities();
355
            //  When we read lastGenerationTime from database
356
            //  then only we should mark the 
357
            //	current time as newLastGenerationTime
358
            if(timeStamp == null) {
359
            	newLastGenerationTime = new Date().getTime();
360
            	lastGenerationTime = CreationUtils.getLastContentGenerationTime();
361
            } else {
362
            	lastGenerationTime = timeStamp.getTime();
363
            }
364
 
3929 mandeep.dh 365
            log.info("lastGenerationTime: " + lastGenerationTime);
366
            if (lastGenerationTime == null) {
2171 rajveer 367
                lastGenerationTime = new Long(0);
3929 mandeep.dh 368
            }
4098 anupam.sin 369
        } 
3929 mandeep.dh 370
 
4680 mandeep.dh 371
        for(EntityState entityState: CreationUtils.getEntitiesState().values()){
372
            long categoryID = entityState.getCategoryID();
4679 mandeep.dh 373
            if(categoryID > 99999){
374
                categoryID = 10000 + categoryID % 100;
4680 mandeep.dh 375
                entityState.setCategoryID(categoryID);
376
                CreationUtils.updateEntityState(entityState);
4679 mandeep.dh 377
            }
378
        }
3929 mandeep.dh 379
        // Filter invalid entities here
2367 rajveer 380
        List<Entity> validEntities = new ArrayList<Entity>();
3929 mandeep.dh 381
        for (long entityID : entities.keySet()) {
382
            if (isValidEntity(entities.get(entityID))) {
383
                validEntities.add(entities.get(entityID));
384
            }
2171 rajveer 385
        }
3929 mandeep.dh 386
 
387
        // Calculate comparison scores
388
        log.info("Calculating comparison scores");
2367 rajveer 389
        NewCMP cmp = new NewCMP(validEntities);
2171 rajveer 390
        Map<Long, Map<Long, Double>> slideScoresByEntity = cmp.getSlideScores();
2367 rajveer 391
        CreationUtils.storeSlideScores(slideScoresByEntity);
2658 rajveer 392
 
3516 rajveer 393
        // Fetch comparison statistics everyday and store them in BDB
3929 mandeep.dh 394
        log.info("Fetching comparison statistics");
3516 rajveer 395
        ComparisonStatsFetcher csf = new ComparisonStatsFetcher();
396
        csf.fetchAndStoreComparisonStats();
3929 mandeep.dh 397
 
398
        // Upload catalog to Google App Engine.
399
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL)) {
400
            log.info("Uploading Catalog to Google app engine");
3083 vikas 401
            List<Item> allItems = client.getAllItems(false);
402
            allItems.addAll(client.getAllItems(true));
403
            CatalogUploderToGAE catalogUploaderToGAE = new CatalogUploderToGAE();
404
            catalogUploaderToGAE.uploadItems(allItems);
405
        }
3929 mandeep.dh 406
 
2726 rajveer 407
        items = client.getAllItemsByStatus(status.ACTIVE);
408
        items.addAll(client.getAllItemsByStatus(status.PAUSED));
409
        items.addAll(client.getAllItemsByStatus(status.CONTENT_COMPLETE));
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.
414
        /*
3929 mandeep.dh 415
        log.info("Finding accessories");
2726 rajveer 416
        AccessoriesFinder af = new AccessoriesFinder(entityIdItemMap.keySet());
3929 mandeep.dh 417
        Map<Long, Map<Long, List<Long>>> relatedAccessories = af.findAccessories();
418
        CreationUtils.storeRelatedAccessories(relatedAccessories);
4677 rajveer 419
         */
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");
436
        SynonymExporter sx = new SynonymExporter(validEntities);
437
        sx.storeSynonyms();
438
 
439
        if (newLastGenerationTime != 0) {
440
            CreationUtils.storeLastContentGenerationTime(newLastGenerationTime);
441
        }
442
 
443
 
444
        log.info("Generating Solr files");
2367 rajveer 445
        NewIR ir = new NewIR(validEntities);
2227 rajveer 446
        ir.exportIRData();
3929 mandeep.dh 447
        // ir.transformIrDataXMLtoSolrXML();
2227 rajveer 448
        ir.exportIRMetaData();
4057 rajveer 449
        ir.transformIrMetaDataXMLtoSolrSchemaXML();
450
        ir.transformIrMetaDataXMLtoSolrCatchAllXML();
2227 rajveer 451
 
3929 mandeep.dh 452
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
453
            List<Item> items = entry.getValue();
454
            for (Item item : items) {
455
                if (item.getItemStatus() == status.CONTENT_COMPLETE) {
2493 rajveer 456
                    item.setItemStatus(status.ACTIVE);
457
                    item.setStatus_description("This item is active");
458
                    client.updateItem(item);
3929 mandeep.dh 459
                }
460
            }
2493 rajveer 461
        }
4472 mandeep.dh 462
        try {
463
            //generate products list that is to be uploaded in Amazon.
4491 amit.gupta 464
            AmazonSCDataGenerator.generateSCProdData(validEntities, GENERATION_TYPE);
4472 mandeep.dh 465
        } catch (Exception e) {
4640 mandeep.dh 466
            log.info("Could not generate Amazon data", e);
4472 mandeep.dh 467
        }
2171 rajveer 468
    }
2367 rajveer 469
 
2171 rajveer 470
    /**
3929 mandeep.dh 471
     * Checks weather entity is valid or not. Entity will be invalid in one of
472
     * these cases:
2367 rajveer 473
     * <ol>
474
     * <li>The entity is not ready.
475
     * <li>The category has not been updated yet. (Set to -1).
476
     * <li>Content has not been updated after last content generation timestamp.
477
     * </ol>
478
     * 
479
     * @param entity
480
     * @return
481
     * @throws Exception
2171 rajveer 482
     */
3929 mandeep.dh 483
    private boolean isValidEntity(Entity entity) throws Exception {
2367 rajveer 484
        ExpandedEntity expEntity = new ExpandedEntity(entity);
485
        EntityState state = CreationUtils.getEntityState(entity.getID());
486
        long categoryID = expEntity.getCategoryID();
3929 mandeep.dh 487
 
488
        if (state.getStatus() != EntityStatus.READY || categoryID == -1) {
2367 rajveer 489
            return false;
490
        }
3929 mandeep.dh 491
        if (state.getMerkedReadyOn().getTime() < this.lastGenerationTime) {
2367 rajveer 492
            return false;
493
        }
494
        return true;
495
    }
496
 
3929 mandeep.dh 497
    private void populateEntityIdItemMap() {
2171 rajveer 498
        Date todate = new Date();
3929 mandeep.dh 499
        for (Item item : items) {
500
            // TODO Can be removed as we are checking in calling function
501
            if (!(item.getItemStatus() == status.ACTIVE
502
                    || item.getItemStatus() == status.CONTENT_COMPLETE || item
503
                    .getItemStatus() == status.PAUSED)) {
2171 rajveer 504
                continue;
505
            }
3929 mandeep.dh 506
            if (todate.getTime() < item.getStartDate()
507
                    || item.getSellingPrice() == 0) {
2171 rajveer 508
                continue;
509
            }
2367 rajveer 510
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
3929 mandeep.dh 511
            if (itemList == null) {
2171 rajveer 512
                itemList = new ArrayList<Item>();
513
            }
514
            itemList.add(item);
515
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
516
        }
2367 rajveer 517
 
3929 mandeep.dh 518
        // Remove all items which have not been updated since last content
519
        // generation.
2171 rajveer 520
        List<Long> removeEntities = new ArrayList<Long>();
3929 mandeep.dh 521
        for (Long entityId : entityIdItemMap.keySet()) {
2171 rajveer 522
            boolean isValidEntity = false;
3929 mandeep.dh 523
            // If any one of the items has been updated before current
524
            // timestamp, than we generate content for whole entity
525
            for (Item item : entityIdItemMap.get(entityId)) {
526
                if (item.getUpdatedOn() > lastGenerationTime) {
2171 rajveer 527
                    isValidEntity = true;
528
                }
529
            }
3929 mandeep.dh 530
            if (!isValidEntity) {
2171 rajveer 531
                removeEntities.add(entityId);
532
            }
533
        }
3929 mandeep.dh 534
        for (Long entityId : removeEntities) {
2171 rajveer 535
            entityIdItemMap.remove(entityId);
536
        }
537
    }
538
}