Subversion Repositories SmartDukaan

Rev

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