Subversion Repositories SmartDukaan

Rev

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