Subversion Repositories SmartDukaan

Rev

Rev 7336 | Rev 7662 | 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;
2733 rajveer 13
import in.shop2020.ui.util.ComparisonStatsFetcher;
3083 vikas 14
import in.shop2020.ui.util.NewVUI;
2367 rajveer 15
import in.shop2020.ui.util.PriceInsertor;
2838 mandeep.dh 16
import in.shop2020.ui.util.SpecialPageJSONConvertor;
6602 amit.gupta 17
import in.shop2020.utils.ConfigClientKeys;
3464 rajveer 18
import in.shop2020.utils.GmailUtils;
2171 rajveer 19
 
3083 vikas 20
import java.io.File;
6871 amit.gupta 21
import java.io.FileNotFoundException;
22
import java.io.FileReader;
3083 vikas 23
import java.io.IOException;
6871 amit.gupta 24
import java.io.Reader;
4098 anupam.sin 25
import java.text.SimpleDateFormat;
3083 vikas 26
import java.util.ArrayList;
27
import java.util.Calendar;
28
import java.util.Date;
29
import java.util.HashMap;
5479 amit.gupta 30
import java.util.Iterator;
3083 vikas 31
import java.util.LinkedHashMap;
32
import java.util.List;
33
import java.util.Map;
2171 rajveer 34
 
3464 rajveer 35
import javax.mail.MessagingException;
36
 
3083 vikas 37
import org.apache.commons.cli.CommandLine;
38
import org.apache.commons.cli.CommandLineParser;
39
import org.apache.commons.cli.HelpFormatter;
40
import org.apache.commons.cli.Options;
41
import org.apache.commons.cli.ParseException;
42
import org.apache.commons.cli.PosixParser;
5227 amit.gupta 43
import org.apache.commons.lang.StringUtils;
3929 mandeep.dh 44
import org.apache.commons.logging.Log;
45
import org.apache.commons.logging.LogFactory;
2171 rajveer 46
 
5084 phani.kuma 47
import com.google.gson.Gson;
6871 amit.gupta 48
import com.google.gson.reflect.TypeToken;
5084 phani.kuma 49
 
3929 mandeep.dh 50
public class ContentGenerationUtility {
51
    private static final String   UPDATE_TYPE_CATALOG         = "CATALOG";
2171 rajveer 52
 
3929 mandeep.dh 53
    private static final String   UPDATE_TYPE_CONTENT         = "CONTENT";
3083 vikas 54
 
4098 anupam.sin 55
    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 56
 
57
    private static Log            log                         = LogFactory
58
                                                                      .getLog(ContentGenerationUtility.class);
5227 amit.gupta 59
    private static long 			ONE_DAY					  = 24*60*60*1000;  	//milliseconds in a day						 	
3929 mandeep.dh 60
    // Commandline options
61
    private static Options        options                     = null;
62
    private static final String   GENERATION_TYPE_INCREMENTAL = "INCREMENTAL";
63
    private static final String   GENERATION_TYPE_ALL         = "ALL";
64
    private static final String   GENERATION_TYPE_ONE         = "ONE";
65
    private static final String   UPDATE_TYPE_OPTION          = "u";
66
    private static final String   GENERATION_TYPE_OPTION      = "t";
67
    private static final String   ENTITY_ID_OPTION            = "e";
4098 anupam.sin 68
    private static final String   TIMESTAMP_OPTION            = "s";
3929 mandeep.dh 69
 
70
    // Default values of cmdline options
71
    private static String         UPDATE_TYPE                 = UPDATE_TYPE_CONTENT;
72
    private static String         GENERATION_TYPE             = GENERATION_TYPE_INCREMENTAL;
73
    private static String         ENTITY_ID                   = "ALL";
5664 amit.gupta 74
    private static String [] 	  DOMAINPATHS 			      = Utils.DOMAIN_NAMES_FOR_CONTENT_GENERATION.split(";");
3929 mandeep.dh 75
 
4098 anupam.sin 76
    private Date 				  timeStamp			  		  = null;
3929 mandeep.dh 77
    private CommandLine           cmd                         = null;
78
    private Map<Long, List<Item>> entityIdItemMap             = new LinkedHashMap<Long, List<Item>>();
79
    private Long                  lastGenerationTime          = 0l;
80
    private Map<Long, Entity>     entities;
81
    private List<Item>            items;
82
    private List<Source>          sources;
83
    private CatalogClient         csc;
84
    private Client                client;
5279 amit.gupta 85
    private List<Item>			  alertItems;	
3929 mandeep.dh 86
    private long                  newLastGenerationTime;
87
 
88
    static {
2171 rajveer 89
        options = new Options();
90
        options.addOption(GENERATION_TYPE_OPTION, true, "Generation type");
3929 mandeep.dh 91
        options.addOption(UPDATE_TYPE_OPTION, true, "Default is : "
92
                + UPDATE_TYPE);
93
        options.addOption(ENTITY_ID_OPTION, true, "all entities " + ENTITY_ID
94
                + " by default");
4098 anupam.sin 95
        options.addOption(TIMESTAMP_OPTION, true, "Manual timestamp");
96
 
2171 rajveer 97
    }
3929 mandeep.dh 98
 
99
    public ContentGenerationUtility() throws Exception {
3127 rajveer 100
        csc = new CatalogClient();
2171 rajveer 101
        client = csc.getClient();
3573 rajveer 102
        sources = client.getAllSources();
5279 amit.gupta 103
        alertItems = new ArrayList<Item>();	
2171 rajveer 104
    }
2367 rajveer 105
 
2171 rajveer 106
    /**
107
     * @param args
3929 mandeep.dh 108
     * @throws Exception
2171 rajveer 109
     */
3929 mandeep.dh 110
    public static void main(String[] args) throws Exception {
6192 amit.gupta 111
        ContentGenerationUtility cgu = new ContentGenerationUtility();
112
 
113
        // Load arguments
114
        cgu.loadArgs(args);
115
 
116
        // Call method based on arguments
117
        cgu.callMethod();
2171 rajveer 118
    }
2367 rajveer 119
 
3929 mandeep.dh 120
    /**
121
     * Validate and set command line arguments. Exit after printing usage if
122
     * anything is astray
123
     * 
124
     * @param args
125
     *            String[] args as featured in public static void main()
2171 rajveer 126
     */
3929 mandeep.dh 127
    private void loadArgs(String[] args) {
2171 rajveer 128
        CommandLineParser parser = new PosixParser();
3929 mandeep.dh 129
 
2171 rajveer 130
        try {
131
            cmd = parser.parse(options, args);
132
        } catch (ParseException e) {
3929 mandeep.dh 133
            log.error("Error parsing arguments", e);
2171 rajveer 134
            System.exit(1);
135
        }
3929 mandeep.dh 136
 
2171 rajveer 137
        // Check for mandatory args
3929 mandeep.dh 138
        if (!(cmd.hasOption(GENERATION_TYPE_OPTION) && cmd
139
                .hasOption(UPDATE_TYPE_OPTION))) {
2171 rajveer 140
            HelpFormatter formatter = new HelpFormatter();
3929 mandeep.dh 141
            formatter.printHelp(COMMAND_LINE, options);
2171 rajveer 142
            System.exit(1);
143
        }
4098 anupam.sin 144
 
145
 
2171 rajveer 146
        GENERATION_TYPE = cmd.getOptionValue(GENERATION_TYPE_OPTION);
4098 anupam.sin 147
 
2367 rajveer 148
        UPDATE_TYPE = cmd.getOptionValue(UPDATE_TYPE_OPTION);
3929 mandeep.dh 149
 
2171 rajveer 150
        // Look for optional args.
3929 mandeep.dh 151
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
152
            if (cmd.hasOption(ENTITY_ID_OPTION)) {
2171 rajveer 153
                ENTITY_ID = cmd.getOptionValue(ENTITY_ID_OPTION);
3929 mandeep.dh 154
            } else {
2171 rajveer 155
                HelpFormatter formatter = new HelpFormatter();
3929 mandeep.dh 156
                formatter.printHelp(COMMAND_LINE, options);
2171 rajveer 157
                System.exit(1);
158
            }
159
        }
4098 anupam.sin 160
 
161
        if (GENERATION_TYPE_INCREMENTAL.equals(GENERATION_TYPE))
162
        	if (cmd.hasOption(TIMESTAMP_OPTION)) {
163
        		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
164
        		try {
165
        		    timeStamp = df.parse(cmd.getOptionValue(TIMESTAMP_OPTION));
166
        		} catch(Exception e) {
167
        			HelpFormatter formatter = new HelpFormatter();
168
                    formatter.printHelp(COMMAND_LINE, options);
169
                    System.exit(1);
170
        		}
171
        	}
2367 rajveer 172
    }
3929 mandeep.dh 173
 
2367 rajveer 174
    /**
175
     * Call method based on arguments
3929 mandeep.dh 176
     * 
2367 rajveer 177
     * @throws Exception
178
     */
3929 mandeep.dh 179
    private void callMethod() {
180
        boolean isSuccess = false;
181
        String logfile = "/tmp/content-from-cms.log";
182
        if (UPDATE_TYPE.equals(UPDATE_TYPE_CONTENT)) {
183
            logfile = "/tmp/content-from-cms.log";
184
            try {
185
                this.generateContent();
186
                isSuccess = true;
187
            } catch (Exception e) {
188
                log.error("Error generating content", e);
189
            }
190
        }
191
 
192
        if (UPDATE_TYPE.equals(UPDATE_TYPE_CATALOG)) {
193
            logfile = "/tmp/content-from-catalog.log";
194
            try {
195
                this.updatePrices();
196
                isSuccess = true;
197
            } catch (Exception e) {
198
                log.error("Error updating prices", e);
199
            }
200
        }
201
 
4969 amit.gupta 202
        GmailUtils gm = new GmailUtils();
7228 amit.gupta 203
        String[] sendTo = { "rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "amit.gupta@shop2020.in" };
4099 anupam.sin 204
 
205
        try {
206
            gm.sendSSLMessage(sendTo, "Content Generation Successful ? : "
207
                    + isSuccess, "Content generation completed at time : "
208
                    + Calendar.getInstance().getTime().toString(),
4311 rajveer 209
                    "build@shop2020.in", "cafe@nes", logfile);
4099 anupam.sin 210
        } catch (MessagingException e) {
211
            log.error("Could not send status mail", e);
4969 amit.gupta 212
        }
2367 rajveer 213
    }
214
 
3929 mandeep.dh 215
    public boolean cleanDir(File dir, boolean deleteSelf) {
216
        if (dir.isDirectory()) {
217
            String[] children = dir.list();
218
            for (int i = 0; i < children.length; i++) {
219
                boolean success = cleanDir(new File(dir, children[i]), true);
220
                if (!success) {
221
                    return false;
222
                }
223
            }
224
        }
225
 
226
        // The directory is now empty so delete it
227
        if (deleteSelf) {
228
            return dir.delete();
229
        }
230
 
231
        return true;
232
    }
233
 
234
    private void removeOldResources() throws IOException {
235
        File f = new File(Utils.EXPORT_SOLR_PATH);
236
        if (f.exists()) {
237
            cleanDir(f, false);
238
        }
5664 amit.gupta 239
 
240
        for(String domainPath : DOMAINPATHS){
241
        	String pathName = domainPath.split("\\.")[0].split(":")[0];
242
        	File f1 = new File(Utils.EXPORT_PATH + "html/entities-" +  pathName);
243
        	if (f1.exists()) {
244
        		cleanDir(f1, false);
245
        	}else {
246
        		f1.mkdir();
247
        	}
3929 mandeep.dh 248
        }
249
    }
250
 
2367 rajveer 251
    /**
252
     * Update the prices in the generated content
3929 mandeep.dh 253
     * 
2367 rajveer 254
     * @throws Exception
255
     */
256
    private void updatePrices() throws Exception {
3929 mandeep.dh 257
        lastGenerationTime = new Long(0);
7506 amit.gupta 258
        List<Long> activeItems = new ArrayList<Long>();
3929 mandeep.dh 259
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
2367 rajveer 260
            items = client.getItemsByCatalogId(Long.parseLong(ENTITY_ID));
5479 amit.gupta 261
            Iterator<Item> it = items.iterator();
262
            while(it.hasNext()){
7506 amit.gupta 263
            	Item ite = it.next();
264
            	status st = ite.getItemStatus();
5479 amit.gupta 265
            	if(!(st.equals(status.ACTIVE) || st.equals(status.PAUSED) || 
7506 amit.gupta 266
            				st.equals(status.COMING_SOON))){
5479 amit.gupta 267
            		it.remove();
268
            	}
7506 amit.gupta 269
            	if(st.equals(status.ACTIVE)){
270
            		activeItems.add(ite.getId());
271
            	}
5479 amit.gupta 272
            }
7506 amit.gupta 273
 
6274 amit.gupta 274
            //ProductListGenerator.updatePriceForEntity(Long.parseLong(ENTITY_ID), items.get(0).getSellingPrice(), items.get(0).getMrp());
3929 mandeep.dh 275
        } else {
6622 rajveer 276
        	log.info("Before getting active items.");
2367 rajveer 277
            items = client.getAllItemsByStatus(status.ACTIVE);
7506 amit.gupta 278
            for (Item item : items) {
279
            	activeItems.add(item.getId());
280
            }
6622 rajveer 281
            log.info("Before getting coming items.");
5227 amit.gupta 282
            items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
6622 rajveer 283
            log.info("Before getting paused items.");
2367 rajveer 284
            items.addAll(client.getAllItemsByStatus(status.PAUSED));
3929 mandeep.dh 285
            // Clean up the data from the solr directories.
6622 rajveer 286
            log.info("Before removing old resources.");
2367 rajveer 287
            removeOldResources();
288
 
289
        }
3929 mandeep.dh 290
 
291
        // this still needs to be evolved. Must not be used.
292
        if (GENERATION_TYPE.equals(GENERATION_TYPE_INCREMENTAL)) {
2367 rajveer 293
        }
294
 
3929 mandeep.dh 295
        // Populate the entityIdIemMap
296
        populateEntityIdItemMap();
6602 amit.gupta 297
        // Generate partners and json objects for phones only
298
        if (!GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
299
        	try	{
7506 amit.gupta 300
	        	ProductListGenerator generator = new ProductListGenerator(entityIdItemMap);
301
 
302
	        	log.info("Before auto suggest json");
303
	        	synonymTitlesExporter();
304
 
305
	        	log.info("Before product list js.");
306
	        	generator.generateProductListJavascript();
307
 
6602 amit.gupta 308
        	} catch (Exception e) {
6623 rajveer 309
        		e.printStackTrace();
6602 amit.gupta 310
        	}
311
 
312
        }
2367 rajveer 313
        PriceInsertor priceInserter = new PriceInsertor();
314
 
6842 amit.gupta 315
        Map<Long,List<String>> entityTags = client.getAllEntityTags();
6871 amit.gupta 316
        Map<Long, Integer> popularityMap = getPolularityMap();
7506 amit.gupta 317
        CatalogClient prod_csc = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(), ConfigClientKeys.catalog_service_server_port.toString());
318
        Client prod_client = prod_csc.getClient();
319
        Map<Long,Boolean> itemsStatus = prod_client.getItemsStatus(activeItems);
3929 mandeep.dh 320
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
321
            long entityId = entry.getKey();
322
            List<Item> items = entry.getValue();
5664 amit.gupta 323
            double minPrice = 0d;
7506 amit.gupta 324
 
325
            //Evaluating availability
326
            String availability = "Out of Stock";
327
            for(Item i: items){
328
            	if(itemsStatus.containsKey(i.getId())) {
329
            		if(itemsStatus.get(i.getId())){
330
            			availability = "In Stock";
331
            			break;
332
            		}
333
            	}else if(i.getItemStatus().equals(status.ACTIVE)){
334
            		availability = "In Stock";
335
            		break;
6602 amit.gupta 336
            	}
337
            }
5664 amit.gupta 338
            StringBuilder priceString = new StringBuilder();
6602 amit.gupta 339
            StringBuilder availabilityString = new StringBuilder();
5664 amit.gupta 340
            boolean domainOnce = true;
5669 amit.gupta 341
            boolean sourceOnce = true;
5664 amit.gupta 342
            for(String domainPath : DOMAINPATHS){
343
            	String domainName = domainPath;
344
            	String pathName = domainPath.split("\\.")[0].split(":")[0];
7279 amit.gupta 345
            	//Special check for store.
7336 amit.gupta 346
            	minPrice = priceInserter.insertPriceInHtml(items, entityId,
347
            			domainName, Utils.EXPORT_PATH + "html/entities-" +  pathName + "/", null);
348
            	if(domainOnce){
349
            		priceString.append("<field name=\"F_50002\">" + minPrice + "</field>");
350
            		availabilityString.append("<field name=\"F_50028\">" + availability + "</field>");
351
            		if(entityTags.containsKey(entityId)) {
352
            			List<String> tags = entityTags.get(entityId);
353
            			for(String tag: tags){
354
            				availabilityString.append("\n<field name=\"F_50029\">" + tag + "</field>");
355
            			}
356
            		}
357
            		if(popularityMap.containsKey(entityId)) {
358
            			availabilityString.append("\n<field name=\"F_50030\">" + popularityMap.get(entityId) + "</field>");
359
            		}else {
360
            			availabilityString.append("\n<field name=\"F_50030\">" + "0" + "</field>");
361
            		}
362
            		domainOnce = false;
5664 amit.gupta 363
            	}
7336 amit.gupta 364
            	if(sources != null){
365
            		for (Source source : sources) {
366
                        minPrice = priceInserter.insertPriceInHtml(items, entityId,
367
                                domainName, Utils.EXPORT_PATH + "html/entities-" + pathName + "/",
368
                                source);
369
                        if(sourceOnce){
370
                        	priceString.append("<field name=\"F_50002_"
371
                                + source.getId() + "\">" + minPrice + "</field>");
372
                        }
373
            		}
374
            		sourceOnce = false;
375
            	}
2367 rajveer 376
            }
3929 mandeep.dh 377
 
378
            priceInserter.insertPriceInSolrData(entityId,
6602 amit.gupta 379
                    priceString.toString(), availabilityString.toString());
2367 rajveer 380
        }
3929 mandeep.dh 381
 
4058 rajveer 382
        priceInserter.copySolrSchemaFiles();
2367 rajveer 383
    }
384
 
7279 amit.gupta 385
	private Map<Long, Integer> getPolularityMap() {
6871 amit.gupta 386
		try {
387
			Reader reader = new FileReader(Utils.EXPORT_PATH + Utils.POPULARITY_JSON);
388
			return new Gson().fromJson(reader, new TypeToken<Map<Long, Integer>>() {}.getType());
389
		} catch (FileNotFoundException e) {
390
			log.error("Could not read popularity file");
391
			e.printStackTrace();
392
			return new HashMap<Long, Integer>();
393
		}
394
 
395
	}
396
 
6602 amit.gupta 397
	/**
2171 rajveer 398
     * Generates content for the specified entity embedding links to the
399
     * specified domain name.
400
     * 
3929 mandeep.dh 401
     * The method will not generate content if one of the following conditions
402
     * is met:
2171 rajveer 403
     * <ol>
404
     * <li>The entity is not ready.
405
     * <li>The category has not been updated yet. (Set to -1).
2367 rajveer 406
     * <li>The content has not been updated.
2171 rajveer 407
     * </ol>
3929 mandeep.dh 408
     * 
2367 rajveer 409
     * @throws
2171 rajveer 410
     */
3929 mandeep.dh 411
    private void generateContent() throws Exception {
412
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL)) {
413
            entities = CreationUtils.getEntities();
2367 rajveer 414
            lastGenerationTime = new Long(0);
7506 amit.gupta 415
            items = client.getAllItemsByStatus(status.CONTENT_COMPLETE);
416
            items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
417
            items.addAll(client.getAllItemsByStatus(status.ACTIVE));
418
            items.addAll(client.getAllItemsByStatus(status.PAUSED));
3929 mandeep.dh 419
        } else if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
420
            entities = new HashMap<Long, Entity>();
421
            entities.put(Long.parseLong(ENTITY_ID),
422
                    CreationUtils.getEntity(Long.parseLong(ENTITY_ID)));
7506 amit.gupta 423
            items = client.getItemsByCatalogId(Long.parseLong(ENTITY_ID));
424
            Iterator<Item> ite = items.iterator();
425
            while(ite.hasNext()) {
426
            	Item i = ite.next();
427
            	if(!(i.getItemStatus().equals(status.ACTIVE) || i.getItemStatus().equals(status.PAUSED) 
428
            	|| i.getItemStatus().equals(status.CONTENT_COMPLETE) || i.getItemStatus().equals(status.COMING_SOON))){
429
            		ite.remove();
430
            	}
431
            }
3929 mandeep.dh 432
            lastGenerationTime = new Long(0);
433
        } else {
4098 anupam.sin 434
        	entities = CreationUtils.getEntities();
435
            //  When we read lastGenerationTime from database
436
            //  then only we should mark the 
437
            //	current time as newLastGenerationTime
438
            if(timeStamp == null) {
439
            	newLastGenerationTime = new Date().getTime();
440
            	lastGenerationTime = CreationUtils.getLastContentGenerationTime();
441
            } else {
442
            	lastGenerationTime = timeStamp.getTime();
443
            }
444
 
3929 mandeep.dh 445
            log.info("lastGenerationTime: " + lastGenerationTime);
446
            if (lastGenerationTime == null) {
2171 rajveer 447
                lastGenerationTime = new Long(0);
3929 mandeep.dh 448
            }
7506 amit.gupta 449
            items = client.getAllItemsByStatus(status.CONTENT_COMPLETE);
450
            items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
4098 anupam.sin 451
        } 
3929 mandeep.dh 452
 
453
        // Filter invalid entities here
2367 rajveer 454
        List<Entity> validEntities = new ArrayList<Entity>();
7506 amit.gupta 455
        List<Long> validEntityIds = new ArrayList<Long>();
456
 
3929 mandeep.dh 457
        for (long entityID : entities.keySet()) {
458
            if (isValidEntity(entities.get(entityID))) {
459
                validEntities.add(entities.get(entityID));
7506 amit.gupta 460
                validEntityIds.add(entityID);
3929 mandeep.dh 461
            }
2171 rajveer 462
        }
3929 mandeep.dh 463
 
464
        // Calculate comparison scores
465
        log.info("Calculating comparison scores");
2367 rajveer 466
        NewCMP cmp = new NewCMP(validEntities);
2171 rajveer 467
        Map<Long, Map<Long, Double>> slideScoresByEntity = cmp.getSlideScores();
2367 rajveer 468
        CreationUtils.storeSlideScores(slideScoresByEntity);
2658 rajveer 469
 
3516 rajveer 470
        // Fetch comparison statistics everyday and store them in BDB
7506 amit.gupta 471
        //This might be remove. 
3929 mandeep.dh 472
        log.info("Fetching comparison statistics");
3516 rajveer 473
        ComparisonStatsFetcher csf = new ComparisonStatsFetcher();
474
        csf.fetchAndStoreComparisonStats();
2726 rajveer 475
        populateEntityIdItemMap();
3929 mandeep.dh 476
 
4677 rajveer 477
 
3929 mandeep.dh 478
        log.info("Writing JSON file for special pages");
2838 mandeep.dh 479
        SpecialPageJSONConvertor bjc = new SpecialPageJSONConvertor();
3929 mandeep.dh 480
        bjc.writeToJSONFile(new File(Utils.EXPORT_JAVASCRIPT_CONTENT_PATH
481
                + "special-pages.json"));
2838 mandeep.dh 482
 
3929 mandeep.dh 483
        log.info("Generating velocity templates, images, documents etc.");
2171 rajveer 484
        NewVUI vui = new NewVUI(lastGenerationTime);
3929 mandeep.dh 485
        for (Entity entity : validEntities) {
486
            log.info("Processing Entityid: " + entity.getID());
487
            vui.generateContentForOneEntity(entity, Utils.EXPORT_VELOCITY_PATH);
2171 rajveer 488
        }
3929 mandeep.dh 489
 
5004 varun.gupt 490
 
3929 mandeep.dh 491
        if (newLastGenerationTime != 0) {
492
            CreationUtils.storeLastContentGenerationTime(newLastGenerationTime);
493
        }
494
 
495
 
496
        log.info("Generating Solr files");
2367 rajveer 497
        NewIR ir = new NewIR(validEntities);
2227 rajveer 498
        ir.exportIRData();
3929 mandeep.dh 499
        // ir.transformIrDataXMLtoSolrXML();
7506 amit.gupta 500
 
501
        if(!GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
502
	        ir.exportIRMetaData();
503
	        ir.transformIrMetaDataXMLtoSolrSchemaXML();
504
	        ir.transformIrMetaDataXMLtoSolrCatchAllXML();
505
        }
2227 rajveer 506
 
3929 mandeep.dh 507
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
508
            List<Item> items = entry.getValue();
509
            for (Item item : items) {
7506 amit.gupta 510
                if ( (item.getItemStatus() == status.CONTENT_COMPLETE && validEntityIds.contains(item.getCatalogItemId())) 
511
                		|| item.getItemStatus() == status.COMING_SOON) {
5360 amit.gupta 512
                	if(item.getStartDate() <= new Date().getTime() + ONE_DAY){
5227 amit.gupta 513
                		item.setItemStatus(status.ACTIVE);
514
                		item.setStatus_description("This item is active");
515
                	} else {
516
                		item.setItemStatus(status.COMING_SOON);
517
                		String productName = getProductName(item);
518
                		String statusDescription = productName + " is coming soon.";
519
                		if(item.getExpectedArrivalDate()>new Date().getTime() + ONE_DAY){
520
                			statusDescription = productName + " will be available by " 
521
                			+ new SimpleDateFormat("dd/MM/yy").format(new Date(item.getExpectedArrivalDate()));
522
                		}
5279 amit.gupta 523
                		//Send alert to Category team one day before expected arrival date
524
                		//So they may change the expected arrival date if they want to.
525
                		if(item.getExpectedArrivalDate() < new Date().getTime() + 2*ONE_DAY && 
526
                				item.getExpectedArrivalDate() > new Date().getTime() + ONE_DAY) {
527
                				alertItems.add(item);
528
                		}
5227 amit.gupta 529
                		item.setStatus_description(statusDescription);
530
                	}
2493 rajveer 531
                    client.updateItem(item);
5279 amit.gupta 532
            	}
3929 mandeep.dh 533
            }
2493 rajveer 534
        }
5279 amit.gupta 535
        sendAlertToCategoryTeam(alertItems);
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();
6876 amit.gupta 541
			String[] recipients = {"amit.gupta@shop2020.in", "chaitnaya.vats@shop2020.in", "khushal.bhatia@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
        }
7506 amit.gupta 642
 
3929 mandeep.dh 643
        for (Long entityId : removeEntities) {
2171 rajveer 644
            entityIdItemMap.remove(entityId);
645
        }
4775 mandeep.dh 646
 
647
        Utils.info("Final valid entities to be processed: " + entityIdItemMap.size());
2171 rajveer 648
    }
5084 phani.kuma 649
 
650
    private void synonymTitlesExporter() {
651
    	SynonymExporter sx = new SynonymExporter();
652
        Map<Long, Map<String,List<String>>> synonyms = sx.getSynonyms();
5453 phani.kuma 653
        Map<String, List<String>> finalsynonyms = new HashMap<String, List<String>>();
5084 phani.kuma 654
    	for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
655
            long entityId = entry.getKey();
656
	    	try{
657
	            String brand = "";
5453 phani.kuma 658
	            String originalModelName = "";
659
	            String originalModelNumber = "";
5084 phani.kuma 660
	            List<String> modelNameSynonyms =  new ArrayList<String>();
661
	            List<String> modelNumberSynonyms =  new ArrayList<String>();
662
	            List<String> titles = new ArrayList<String>();
663
	            Map<String,List<String>> synonymMap = synonyms.get(entityId);
664
	            if(synonymMap != null && !synonymMap.isEmpty()){
665
	            	if(synonymMap.get("ORIGINAL_MODEL_NAME") != null && !synonymMap.get("ORIGINAL_MODEL_NAME").isEmpty()){
666
	            		modelNameSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NAME"));
5453 phani.kuma 667
	            		originalModelName = synonymMap.get("ORIGINAL_MODEL_NAME").get(0);
5084 phani.kuma 668
	            	}
669
	            	if(synonymMap.get("MODEL_NAME") != null && !synonymMap.get("MODEL_NAME").isEmpty()){
670
	            		modelNameSynonyms.addAll(synonymMap.get("MODEL_NAME"));
671
	            	}
672
	            	if(synonymMap.get("ORIGINAL_MODEL_NUMBER") != null && !synonymMap.get("ORIGINAL_MODEL_NUMBER").isEmpty()){
673
	            		modelNumberSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NUMBER"));
5453 phani.kuma 674
	            		originalModelNumber = synonymMap.get("ORIGINAL_MODEL_NUMBER").get(0);
5084 phani.kuma 675
	            	}
676
	            	if(synonymMap.get("MODEL_NUMBER") != null && !synonymMap.get("MODEL_NUMBER").isEmpty()){
677
	            		modelNumberSynonyms.addAll(synonymMap.get("MODEL_NUMBER"));
678
	            	}
679
	            	brand = ((synonymMap.get("ORIGINAL_BRAND") != null && !synonymMap.get("ORIGINAL_BRAND").isEmpty()) ? synonymMap.get("ORIGINAL_BRAND").get(0) : "");
680
	            }
681
	            for(String model_name: modelNameSynonyms){
682
	            	for(String model_number: modelNumberSynonyms){
683
	            		String title = brand + " " + model_name + " " + model_number;
684
	            		title = title.replaceAll("  ", " ");
685
	            		titles.add(title);
686
	            	}
687
	            }
5453 phani.kuma 688
	            String originaltitle = brand + " " + originalModelName + " " + originalModelNumber;
689
	            originaltitle = originaltitle.replaceAll("  ", " ");
690
	            originaltitle = originaltitle.trim();
691
	            if(!originaltitle.isEmpty()) {
692
	            	finalsynonyms.put(originaltitle, titles);
693
	            }
5084 phani.kuma 694
	        } catch (Exception e) {
695
				e.printStackTrace();
696
			}
697
    	}
698
 
699
    	String autosuggestFilename = Utils.EXPORT_JAVASCRIPT_CONTENT_PATH + "autosuggest.json";
700
        Gson gson = new Gson();
701
		try {
702
			DBUtils.store(gson.toJson(finalsynonyms), autosuggestFilename);
703
		} catch (Exception e) {
704
			e.printStackTrace();
705
		}
706
    }
2171 rajveer 707
}