Subversion Repositories SmartDukaan

Rev

Rev 6623 | Rev 6871 | 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
 
6842 amit.gupta 321
        Map<Long,List<String>> entityTags = client.getAllEntityTags();
3929 mandeep.dh 322
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
323
            long entityId = entry.getKey();
324
            List<Item> items = entry.getValue();
5664 amit.gupta 325
	            // TODO Domain name and destination directory should be read from
326
	            // properties file
327
            double minPrice = 0d;
6602 amit.gupta 328
            String availability = "In Stock";
329
            if (inStockEntities != null ) {
330
            	if (!inStockEntities.contains(entry.getKey())) {
331
            		availability = "Out of Stock";
332
            	}
333
            } else {
334
            	availability = getAvaialability(entry.getValue());
335
            }
5664 amit.gupta 336
            StringBuilder priceString = new StringBuilder();
6602 amit.gupta 337
            StringBuilder availabilityString = new StringBuilder();
5664 amit.gupta 338
            boolean domainOnce = true;
5669 amit.gupta 339
            boolean sourceOnce = true;
5664 amit.gupta 340
            for(String domainPath : DOMAINPATHS){
341
            	String domainName = domainPath;
342
            	String pathName = domainPath.split("\\.")[0].split(":")[0];
343
            	minPrice = priceInserter.insertPriceInHtml(items, entityId,
344
            			domainName, Utils.EXPORT_PATH + "html/entities-" +  pathName + "/", null);
345
            	if(domainOnce){
6602 amit.gupta 346
            		priceString.append("<field name=\"F_50002\">" + minPrice + "</field>");
6607 amit.gupta 347
            		availabilityString.append("<field name=\"F_50028\">" + availability + "</field>");
6842 amit.gupta 348
            		if(entityTags.containsKey(entityId)) {
349
            			List<String> tags = entityTags.get(entityId);
350
            			for(String tag: tags){
351
            				availabilityString.append("\n<field name=\"F_50029\">" + tag + "</field>");
352
            			}
353
            		}
5664 amit.gupta 354
            		domainOnce = false;
355
            	}
356
            	if(sources != null){
357
            		for (Source source : sources) {
358
                        minPrice = priceInserter.insertPriceInHtml(items, entityId,
359
                                domainName, Utils.EXPORT_PATH + "html/entities-" + pathName + "/",
360
                                source);
361
                        if(sourceOnce){
362
                        	priceString.append("<field name=\"F_50002_"
363
                                + source.getId() + "\">" + minPrice + "</field>");
364
                        }
365
            		}
5669 amit.gupta 366
            		sourceOnce = false;
5664 amit.gupta 367
            	}
2367 rajveer 368
            }
3929 mandeep.dh 369
 
370
            priceInserter.insertPriceInSolrData(entityId,
6602 amit.gupta 371
                    priceString.toString(), availabilityString.toString());
2367 rajveer 372
        }
3929 mandeep.dh 373
 
4058 rajveer 374
        priceInserter.copySolrSchemaFiles();
5084 phani.kuma 375
        synonymTitlesExporter();
2367 rajveer 376
    }
377
 
6602 amit.gupta 378
    private String getAvaialability(List<Item> value) {
379
    	boolean isActive = true;
380
    	try {
381
			Client catalogClientProd = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(), ConfigClientKeys.catalog_service_server_port.toString()).getClient();
382
			for (Item item : value ) {
383
				if (item.getItemStatus().equals(status.ACTIVE)) {
384
					if(item.isRisky()){
385
	    				try {
386
	    					ItemShippingInfo isi = catalogClientProd.isActive(item.getId());
387
	    					isActive = isi.isIsActive();
388
	    				} catch (Exception e) {
389
	    					e.printStackTrace();
390
	    					isActive = true;
391
	    				}
392
	    			}
393
				}
394
				if(isActive) break;
395
			}
396
		} catch (TTransportException e) {
397
			// TODO Auto-generated catch block
398
			e.printStackTrace();
399
		}
400
		return isActive ? "In Stock" : "Out of Stock";
401
	}
402
 
403
	/**
2171 rajveer 404
     * Generates content for the specified entity embedding links to the
405
     * specified domain name.
406
     * 
3929 mandeep.dh 407
     * The method will not generate content if one of the following conditions
408
     * is met:
2171 rajveer 409
     * <ol>
410
     * <li>The entity is not ready.
411
     * <li>The category has not been updated yet. (Set to -1).
2367 rajveer 412
     * <li>The content has not been updated.
2171 rajveer 413
     * </ol>
3929 mandeep.dh 414
     * 
2367 rajveer 415
     * @throws
2171 rajveer 416
     */
3929 mandeep.dh 417
    private void generateContent() throws Exception {
418
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL)) {
419
            entities = CreationUtils.getEntities();
2367 rajveer 420
            lastGenerationTime = new Long(0);
3929 mandeep.dh 421
        } else if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
422
            entities = new HashMap<Long, Entity>();
423
            entities.put(Long.parseLong(ENTITY_ID),
424
                    CreationUtils.getEntity(Long.parseLong(ENTITY_ID)));
425
            lastGenerationTime = new Long(0);
426
        } else {
4098 anupam.sin 427
        	entities = CreationUtils.getEntities();
428
            //  When we read lastGenerationTime from database
429
            //  then only we should mark the 
430
            //	current time as newLastGenerationTime
431
            if(timeStamp == null) {
432
            	newLastGenerationTime = new Date().getTime();
433
            	lastGenerationTime = CreationUtils.getLastContentGenerationTime();
434
            } else {
435
            	lastGenerationTime = timeStamp.getTime();
436
            }
437
 
3929 mandeep.dh 438
            log.info("lastGenerationTime: " + lastGenerationTime);
439
            if (lastGenerationTime == null) {
2171 rajveer 440
                lastGenerationTime = new Long(0);
3929 mandeep.dh 441
            }
4098 anupam.sin 442
        } 
3929 mandeep.dh 443
 
444
        // Filter invalid entities here
2367 rajveer 445
        List<Entity> validEntities = new ArrayList<Entity>();
3929 mandeep.dh 446
        for (long entityID : entities.keySet()) {
447
            if (isValidEntity(entities.get(entityID))) {
448
                validEntities.add(entities.get(entityID));
449
            }
2171 rajveer 450
        }
3929 mandeep.dh 451
 
452
        // Calculate comparison scores
453
        log.info("Calculating comparison scores");
2367 rajveer 454
        NewCMP cmp = new NewCMP(validEntities);
2171 rajveer 455
        Map<Long, Map<Long, Double>> slideScoresByEntity = cmp.getSlideScores();
2367 rajveer 456
        CreationUtils.storeSlideScores(slideScoresByEntity);
2658 rajveer 457
 
3516 rajveer 458
        // Fetch comparison statistics everyday and store them in BDB
3929 mandeep.dh 459
        log.info("Fetching comparison statistics");
3516 rajveer 460
        ComparisonStatsFetcher csf = new ComparisonStatsFetcher();
461
        csf.fetchAndStoreComparisonStats();
3929 mandeep.dh 462
 
463
        // Upload catalog to Google App Engine.
464
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL)) {
465
            log.info("Uploading Catalog to Google app engine");
3083 vikas 466
            List<Item> allItems = client.getAllItems(false);
467
            allItems.addAll(client.getAllItems(true));
468
            CatalogUploderToGAE catalogUploaderToGAE = new CatalogUploderToGAE();
469
            catalogUploaderToGAE.uploadItems(allItems);
470
        }
3929 mandeep.dh 471
 
2726 rajveer 472
        items = client.getAllItemsByStatus(status.ACTIVE);
473
        items.addAll(client.getAllItemsByStatus(status.PAUSED));
474
        items.addAll(client.getAllItemsByStatus(status.CONTENT_COMPLETE));
5227 amit.gupta 475
        items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
2726 rajveer 476
        populateEntityIdItemMap();
3929 mandeep.dh 477
 
4677 rajveer 478
        //FIXME Avoiding the finding of accesories, as list of categories for which we need to find accessories is hardocoded in code. 
479
        // We need to make that configurable. Also creating ticket to improve it.
5106 rajveer 480
        try{
481
	        log.info("Finding accessories");
5404 amit.gupta 482
	        AccessoriesFinder af = new AccessoriesFinder(new HashSet<Long>(allValidEntityIds));
5106 rajveer 483
	        Map<Long, Map<Long, List<Long>>> relatedAccessories = af.findAccessories();
484
	        CreationUtils.storeRelatedAccessories(relatedAccessories);
485
        }catch (Exception e) {
486
        	log.error("Error while generating accessories" + e);
487
		}
4677 rajveer 488
 
3929 mandeep.dh 489
        log.info("Writing JSON file for special pages");
2838 mandeep.dh 490
        SpecialPageJSONConvertor bjc = new SpecialPageJSONConvertor();
3929 mandeep.dh 491
        bjc.writeToJSONFile(new File(Utils.EXPORT_JAVASCRIPT_CONTENT_PATH
492
                + "special-pages.json"));
2838 mandeep.dh 493
 
3929 mandeep.dh 494
        log.info("Generating velocity templates, images, documents etc.");
2171 rajveer 495
        NewVUI vui = new NewVUI(lastGenerationTime);
3929 mandeep.dh 496
        for (Entity entity : validEntities) {
497
            log.info("Processing Entityid: " + entity.getID());
498
            vui.generateContentForOneEntity(entity, Utils.EXPORT_VELOCITY_PATH);
2171 rajveer 499
        }
3929 mandeep.dh 500
 
501
        // Generate synonyms list. This will be used in PriceComparisonTool to
502
        // resolve the product names.
503
        log.info("Generating synonyms");
5084 phani.kuma 504
        SynonymExporter sx = new SynonymExporter();
505
        sx.storeSynonyms(validEntities);
5004 varun.gupt 506
 
5155 varun.gupt 507
        List<Entity> allValidEntities;
508
 
509
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL))	{
510
        	allValidEntities = validEntities;
511
 
512
        } else	{
513
        	allValidEntities = new ArrayList<Entity>();
5404 amit.gupta 514
			for (Long entityId : allValidEntityIds)	{
515
				allValidEntities.add(CreationUtils.getEntity(entityId));
5155 varun.gupt 516
			}
517
        }
518
 
5004 varun.gupt 519
        log.info("Generating HTML for Site Index");
5155 varun.gupt 520
        ProductIndexGenerator indexGenerator = new ProductIndexGenerator(allValidEntities);
5004 varun.gupt 521
        indexGenerator.generate();
5642 amit.gupta 522
 
523
        log.info("Generating HTML for Site for Product Documents");
524
        ProductDocumentsGenerator asGenerator = new ProductDocumentsGenerator(allValidEntities);
525
        asGenerator.generate();
5004 varun.gupt 526
 
5117 varun.gupt 527
        log.info("Generating HTML for Accessories Compatibility Index");
5155 varun.gupt 528
        CompatibleAccessoriesIndexGenerator generator = new CompatibleAccessoriesIndexGenerator(allValidEntities);
5117 varun.gupt 529
        generator.generate();
5600 amit.gupta 530
 
5604 amit.gupta 531
        log.info("Generating HTML for Most Frequently searched keywords");
5600 amit.gupta 532
        MostFrequentlySearchedKeywords mfsk = new MostFrequentlySearchedKeywords();
5604 amit.gupta 533
        mfsk.generate();
5117 varun.gupt 534
 
5315 varun.gupt 535
        log.info("Generating HTML for Most Compared Index");
5425 amit.gupta 536
        MostComparedIndexGenerator mostCompGenerator = new MostComparedIndexGenerator(allValidEntityIds);
5315 varun.gupt 537
        mostCompGenerator.generate();
5522 varun.gupt 538
 
539
        log.info("Generating XML for Mobile Site XML feed");
540
        MobileSiteDataXMLGenerator mSiteXMLGenerator = new MobileSiteDataXMLGenerator(allValidEntities);
541
        mSiteXMLGenerator.generate();
5315 varun.gupt 542
 
3929 mandeep.dh 543
        if (newLastGenerationTime != 0) {
544
            CreationUtils.storeLastContentGenerationTime(newLastGenerationTime);
545
        }
546
 
547
 
548
        log.info("Generating Solr files");
2367 rajveer 549
        NewIR ir = new NewIR(validEntities);
2227 rajveer 550
        ir.exportIRData();
3929 mandeep.dh 551
        // ir.transformIrDataXMLtoSolrXML();
2227 rajveer 552
        ir.exportIRMetaData();
4057 rajveer 553
        ir.transformIrMetaDataXMLtoSolrSchemaXML();
554
        ir.transformIrMetaDataXMLtoSolrCatchAllXML();
2227 rajveer 555
 
3929 mandeep.dh 556
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
557
            List<Item> items = entry.getValue();
558
            for (Item item : items) {
5227 amit.gupta 559
                if (item.getItemStatus() == status.CONTENT_COMPLETE || item.getItemStatus() == status.COMING_SOON) {
5360 amit.gupta 560
                	if(item.getStartDate() <= new Date().getTime() + ONE_DAY){
5227 amit.gupta 561
                		item.setItemStatus(status.ACTIVE);
562
                		item.setStatus_description("This item is active");
563
                	} else {
564
                		item.setItemStatus(status.COMING_SOON);
565
                		String productName = getProductName(item);
566
                		String statusDescription = productName + " is coming soon.";
567
                		if(item.getExpectedArrivalDate()>new Date().getTime() + ONE_DAY){
568
                			statusDescription = productName + " will be available by " 
569
                			+ new SimpleDateFormat("dd/MM/yy").format(new Date(item.getExpectedArrivalDate()));
570
                		}
5279 amit.gupta 571
                		//Send alert to Category team one day before expected arrival date
572
                		//So they may change the expected arrival date if they want to.
573
                		if(item.getExpectedArrivalDate() < new Date().getTime() + 2*ONE_DAY && 
574
                				item.getExpectedArrivalDate() > new Date().getTime() + ONE_DAY) {
575
                				alertItems.add(item);
576
                		}
5227 amit.gupta 577
                		item.setStatus_description(statusDescription);
578
                	}
2493 rajveer 579
                    client.updateItem(item);
5279 amit.gupta 580
            	}
3929 mandeep.dh 581
            }
2493 rajveer 582
        }
5279 amit.gupta 583
        sendAlertToCategoryTeam(alertItems);
4472 mandeep.dh 584
        try {
585
            //generate products list that is to be uploaded in Amazon.
5901 amit.gupta 586
        	AmazonSCDataGenerator ascdGenerator = new AmazonSCDataGenerator(validEntities, GENERATION_TYPE);
587
            ascdGenerator.generateSCProdData();
4472 mandeep.dh 588
        } catch (Exception e) {
4994 amit.gupta 589
        	e.printStackTrace();
4640 mandeep.dh 590
            log.info("Could not generate Amazon data", e);
4472 mandeep.dh 591
        }
2171 rajveer 592
    }
2367 rajveer 593
 
5279 amit.gupta 594
    private void sendAlertToCategoryTeam(List<Item> items) {
595
    	if(items!=null && items.size()!=0){
596
			GmailUtils util = new GmailUtils();
5280 amit.gupta 597
			String[] recipients = {"amit.gupta@shop2020.in", "chaitnaya.vats@shop2020.in", "ashutosh.saxena@shop2020.in"};
5279 amit.gupta 598
			String from = "build@shop2020.in";
599
			String password = "cafe@nes";
600
			String subject = Utils.EXPECTED_ARRIVAL_ACHIEVED_TEMPLATE;
601
			StringBuffer message = new StringBuffer("Please check the following items:\n");
602
			List<File> emptyList = new ArrayList<File>();
603
			for( Item item : items){
604
				message.append("\t" + getProductName(item));
605
			}
606
			try {
607
				util.sendSSLMessage(recipients, subject, message.toString(), from, password, emptyList);
608
			} catch (Exception e){
609
				log.info("Could not send alert" + e);
610
			}
611
    	}
612
	}
613
 
614
	private String getProductName(Item item) {
5227 amit.gupta 615
    	String brand = item.getBrand();
616
		String modelName = item.getModelName();
617
		String modelNumber = item.getModelNumber();
618
		String product = "";
619
		if(StringUtils.isEmpty(modelName)){
620
			product = brand + " " + modelNumber;
621
		}else {
622
			product = brand + " " + modelName + " " + modelNumber;
623
		}
624
		return product;
625
	}
626
 
2171 rajveer 627
    /**
3929 mandeep.dh 628
     * Checks weather entity is valid or not. Entity will be invalid in one of
629
     * these cases:
2367 rajveer 630
     * <ol>
631
     * <li>The entity is not ready.
632
     * <li>The category has not been updated yet. (Set to -1).
633
     * <li>Content has not been updated after last content generation timestamp.
634
     * </ol>
635
     * 
636
     * @param entity
637
     * @return
638
     * @throws Exception
2171 rajveer 639
     */
3929 mandeep.dh 640
    private boolean isValidEntity(Entity entity) throws Exception {
2367 rajveer 641
        ExpandedEntity expEntity = new ExpandedEntity(entity);
642
        EntityState state = CreationUtils.getEntityState(entity.getID());
643
        long categoryID = expEntity.getCategoryID();
3929 mandeep.dh 644
 
645
        if (state.getStatus() != EntityStatus.READY || categoryID == -1) {
2367 rajveer 646
            return false;
647
        }
3929 mandeep.dh 648
        if (state.getMerkedReadyOn().getTime() < this.lastGenerationTime) {
2367 rajveer 649
            return false;
650
        }
651
        return true;
652
    }
653
 
3929 mandeep.dh 654
    private void populateEntityIdItemMap() {
2171 rajveer 655
        Date todate = new Date();
4775 mandeep.dh 656
        Utils.info("Processing " + items.size() + " items");
3929 mandeep.dh 657
        for (Item item : items) {
4778 mandeep.dh 658
            Utils.info(item.getId() + ":" + item.getItemStatus() + ":" + item.getCatalogItemId());
3929 mandeep.dh 659
            // TODO Can be removed as we are checking in calling function
660
            if (!(item.getItemStatus() == status.ACTIVE
661
                    || item.getItemStatus() == status.CONTENT_COMPLETE || item
5227 amit.gupta 662
                    .getItemStatus() == status.PAUSED || item.getItemStatus() == status.COMING_SOON)) {
2171 rajveer 663
                continue;
664
            }
4777 mandeep.dh 665
            Utils.info(item.getStartDate() + ":" + item.getSellingPrice());
5227 amit.gupta 666
 
667
			if (todate.getTime() < item.getStartDate()
668
					&& (!item.isSetExpectedArrivalDate() || todate.getTime() < item.getComingSoonStartDate()) 
669
					|| item.getSellingPrice() == 0) {
670
				continue;
671
			}
4777 mandeep.dh 672
            Utils.info(item.getId() + " Item is adding");
2367 rajveer 673
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
3929 mandeep.dh 674
            if (itemList == null) {
2171 rajveer 675
                itemList = new ArrayList<Item>();
5227 amit.gupta 676
            } 
2171 rajveer 677
            itemList.add(item);
678
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
679
        }
2367 rajveer 680
 
4775 mandeep.dh 681
        Utils.info("Processing " + entityIdItemMap.size() + " entities");
3929 mandeep.dh 682
        // Remove all items which have not been updated since last content
683
        // generation.
2171 rajveer 684
        List<Long> removeEntities = new ArrayList<Long>();
3929 mandeep.dh 685
        for (Long entityId : entityIdItemMap.keySet()) {
2171 rajveer 686
            boolean isValidEntity = false;
3929 mandeep.dh 687
            // If any one of the items has been updated before current
688
            // timestamp, than we generate content for whole entity
689
            for (Item item : entityIdItemMap.get(entityId)) {
5227 amit.gupta 690
                if (item.getUpdatedOn() > lastGenerationTime || item.getItemStatus()==status.COMING_SOON) {
2171 rajveer 691
                    isValidEntity = true;
692
                }
693
            }
3929 mandeep.dh 694
            if (!isValidEntity) {
2171 rajveer 695
                removeEntities.add(entityId);
696
            }
697
        }
5404 amit.gupta 698
        //Simply assign allValidEntityIds to a class variable as these need to be used where all valid entites
699
        //are needed.
700
        allValidEntityIds = new ArrayList<Long>(entityIdItemMap.keySet());
3929 mandeep.dh 701
        for (Long entityId : removeEntities) {
2171 rajveer 702
            entityIdItemMap.remove(entityId);
703
        }
4775 mandeep.dh 704
 
705
        Utils.info("Final valid entities to be processed: " + entityIdItemMap.size());
2171 rajveer 706
    }
5084 phani.kuma 707
 
708
    private void synonymTitlesExporter() {
709
    	SynonymExporter sx = new SynonymExporter();
710
        Map<Long, Map<String,List<String>>> synonyms = sx.getSynonyms();
5453 phani.kuma 711
        Map<String, List<String>> finalsynonyms = new HashMap<String, List<String>>();
5084 phani.kuma 712
    	for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
713
            long entityId = entry.getKey();
714
	    	try{
715
	            String brand = "";
5453 phani.kuma 716
	            String originalModelName = "";
717
	            String originalModelNumber = "";
5084 phani.kuma 718
	            List<String> modelNameSynonyms =  new ArrayList<String>();
719
	            List<String> modelNumberSynonyms =  new ArrayList<String>();
720
	            List<String> titles = new ArrayList<String>();
721
	            Map<String,List<String>> synonymMap = synonyms.get(entityId);
722
	            if(synonymMap != null && !synonymMap.isEmpty()){
723
	            	if(synonymMap.get("ORIGINAL_MODEL_NAME") != null && !synonymMap.get("ORIGINAL_MODEL_NAME").isEmpty()){
724
	            		modelNameSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NAME"));
5453 phani.kuma 725
	            		originalModelName = synonymMap.get("ORIGINAL_MODEL_NAME").get(0);
5084 phani.kuma 726
	            	}
727
	            	if(synonymMap.get("MODEL_NAME") != null && !synonymMap.get("MODEL_NAME").isEmpty()){
728
	            		modelNameSynonyms.addAll(synonymMap.get("MODEL_NAME"));
729
	            	}
730
	            	if(synonymMap.get("ORIGINAL_MODEL_NUMBER") != null && !synonymMap.get("ORIGINAL_MODEL_NUMBER").isEmpty()){
731
	            		modelNumberSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NUMBER"));
5453 phani.kuma 732
	            		originalModelNumber = synonymMap.get("ORIGINAL_MODEL_NUMBER").get(0);
5084 phani.kuma 733
	            	}
734
	            	if(synonymMap.get("MODEL_NUMBER") != null && !synonymMap.get("MODEL_NUMBER").isEmpty()){
735
	            		modelNumberSynonyms.addAll(synonymMap.get("MODEL_NUMBER"));
736
	            	}
737
	            	brand = ((synonymMap.get("ORIGINAL_BRAND") != null && !synonymMap.get("ORIGINAL_BRAND").isEmpty()) ? synonymMap.get("ORIGINAL_BRAND").get(0) : "");
738
	            }
739
	            for(String model_name: modelNameSynonyms){
740
	            	for(String model_number: modelNumberSynonyms){
741
	            		String title = brand + " " + model_name + " " + model_number;
742
	            		title = title.replaceAll("  ", " ");
743
	            		titles.add(title);
744
	            	}
745
	            }
5453 phani.kuma 746
	            String originaltitle = brand + " " + originalModelName + " " + originalModelNumber;
747
	            originaltitle = originaltitle.replaceAll("  ", " ");
748
	            originaltitle = originaltitle.trim();
749
	            if(!originaltitle.isEmpty()) {
750
	            	finalsynonyms.put(originaltitle, titles);
751
	            }
5084 phani.kuma 752
	        } catch (Exception e) {
753
				e.printStackTrace();
754
			}
755
    	}
756
 
757
    	String autosuggestFilename = Utils.EXPORT_JAVASCRIPT_CONTENT_PATH + "autosuggest.json";
758
        Gson gson = new Gson();
759
		try {
760
			DBUtils.store(gson.toJson(finalsynonyms), autosuggestFilename);
761
		} catch (Exception e) {
762
			e.printStackTrace();
763
		}
764
    }
2171 rajveer 765
}