Subversion Repositories SmartDukaan

Rev

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