Subversion Repositories SmartDukaan

Rev

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