Subversion Repositories SmartDukaan

Rev

Rev 6040 | Rev 6602 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1678 rajveer 1
package in.shop2020.util;
2
 
5113 amit.gupta 3
import in.shop2020.logistics.DeliveryType;
4
import in.shop2020.logistics.LogisticsInfo;
5
import in.shop2020.logistics.LogisticsService;
4188 varun.gupt 6
import in.shop2020.metamodel.core.Entity;
4802 amit.gupta 7
import in.shop2020.metamodel.definitions.Catalog;
6025 amit.gupta 8
import in.shop2020.metamodel.definitions.Category;
4802 amit.gupta 9
import in.shop2020.metamodel.definitions.DefinitionsContainer;
4188 varun.gupt 10
import in.shop2020.metamodel.util.CreationUtils;
5945 mandeep.dh 11
import in.shop2020.model.v1.catalog.CatalogService.Client;
1678 rajveer 12
import in.shop2020.model.v1.catalog.Item;
6025 amit.gupta 13
import in.shop2020.model.v1.catalog.ItemShippingInfo;
5612 amit.gupta 14
import in.shop2020.model.v1.catalog.VoucherItemMapping;
4188 varun.gupt 15
import in.shop2020.model.v1.catalog.status;
16
import in.shop2020.model.v1.user.ItemCouponDiscount;
17
import in.shop2020.thrift.clients.CatalogClient;
5113 amit.gupta 18
import in.shop2020.thrift.clients.LogisticsClient;
4188 varun.gupt 19
import in.shop2020.thrift.clients.PromotionClient;
6027 amit.gupta 20
import in.shop2020.utils.ConfigClientKeys;
4188 varun.gupt 21
 
2130 rajveer 22
import java.io.File;
5612 amit.gupta 23
import java.io.FileInputStream;
24
import java.io.IOException;
25
import java.nio.MappedByteBuffer;
26
import java.nio.channels.FileChannel;
27
import java.nio.charset.Charset;
1678 rajveer 28
import java.util.ArrayList;
5612 amit.gupta 29
import java.util.Arrays;
4188 varun.gupt 30
import java.util.Date;
4143 varun.gupt 31
import java.util.HashMap;
1678 rajveer 32
import java.util.List;
33
import java.util.Map;
34
 
4202 varun.gupt 35
import org.apache.commons.lang.StringEscapeUtils;
1678 rajveer 36
import org.apache.commons.lang.StringUtils;
4143 varun.gupt 37
import org.json.JSONObject;
1678 rajveer 38
 
6257 rajveer 39
import org.w3c.dom.*;
40
import org.apache.xerces.parsers.DOMParser;
41
 
42
import javax.xml.transform.*;
43
import javax.xml.transform.dom.DOMSource;
44
import javax.xml.transform.stream.StreamResult;
45
 
1678 rajveer 46
/**
47
 * Command line utility to generate xml file for partners
48
 * 
49
 * @author rajveer
50
 *
51
 */
52
public class ProductListGenerator {
53
 
54
	private String[] xmlIndentation = {"", "    ", "        ", "            ","                "};
5612 amit.gupta 55
	private Client cc = null;
6025 amit.gupta 56
	List <Long> catalogItemIds = new ArrayList<Long>();
2367 rajveer 57
	public Map<Long, List<Item>> entityIdItemMap;
5113 amit.gupta 58
	private static final String DEFAULT_PINCODE = "110001";
4802 amit.gupta 59
	DefinitionsContainer defContainer = Catalog.getInstance().getDefinitionsContainer();
6025 amit.gupta 60
	private List<Long> validParentCategories = Arrays.asList((long)Utils.LAPTOPS_CATEGORY, (long)Utils.CAMERAS_CATEGORY, (long)Utils.MOBILE_PHONES_CATAGORY, (long)Utils.TABLETS_CATEGORY);
5612 amit.gupta 61
	private List<Long> voucherEntities = new ArrayList<Long>();
1678 rajveer 62
 
2367 rajveer 63
	public ProductListGenerator(Map<Long, List<Item>> entityIdItemMap) throws Exception {
64
		this.entityIdItemMap = entityIdItemMap;
5612 amit.gupta 65
		String vouchers = readFile(Utils.CONTENT_DB_PATH + "voucher-entities.txt");
66
		for (String voucher : vouchers.split(",")){
67
			voucherEntities.add(Long.parseLong(voucher.trim()));
68
		}
1678 rajveer 69
	}
70
 
71
 
72
	/**
2367 rajveer 73
	 * Get the url of the entity
1678 rajveer 74
	 * @param expEntity
75
	 * @return url
76
	 */
2367 rajveer 77
	private String getProductURL(long entityId, Item item){
4802 amit.gupta 78
		//long rootCategoryId = catm.getCategory(item.getCategory()).getParent_category_id();
79
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
80
 
81
		String url = "http://www.saholic.com/" + parentCategory.getLabel().toLowerCase().replace(' ', '-') + "/";
2367 rajveer 82
		String productUrl = ((item.getBrand() != null) ? item.getBrand().trim() + " " : "").toLowerCase().replace(' ', '-')
83
        + "-" + ((item.getModelName() != null) ? item.getModelName().trim() + " " : "").toLowerCase().replace(' ', '-') 
84
	    + "-" + (( item.getModelNumber() != null ) ? item.getModelNumber().trim() + " ": "" ).toLowerCase().replace(' ', '-')
85
        + "-" + entityId;
1678 rajveer 86
		productUrl = productUrl.replaceAll("/", "-");
87
		url = url + productUrl;
2367 rajveer 88
		url = url.replaceAll("-+", "-");
1678 rajveer 89
		return url;
90
	}
6040 amit.gupta 91
 
92
 
93
	/**
94
	 * Get the url of the entity
95
	 * @param expEntity
96
	 * @return url
97
	 */
98
	private String getProductURL(long entityId, Item item, int affiliateId){
99
		//long rootCategoryId = catm.getCategory(item.getCategory()).getParent_category_id();
100
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
101
 
102
		String url = "http://www.saholic.com/" + parentCategory.getLabel().toLowerCase().replace(' ', '-') + "/";
103
		String productUrl = ((item.getBrand() != null) ? item.getBrand().trim() + " " : "").toLowerCase().replace(' ', '-')
104
		+ "-" + ((item.getModelName() != null) ? item.getModelName().trim() + " " : "").toLowerCase().replace(' ', '-') 
105
		+ "-" + (( item.getModelNumber() != null ) ? item.getModelNumber().trim() + " ": "" ).toLowerCase().replace(' ', '-')
106
		+ "-" + entityId;
107
		productUrl = productUrl.replaceAll("/", "-");
108
		url = url + productUrl;
109
		url = url.replaceAll("-+", "-");
110
		return url + "?afid=" + affiliateId;
111
	}
1678 rajveer 112
 
2367 rajveer 113
 
114
 
1678 rajveer 115
	/**
3964 rajveer 116
	 * Get the minimum mrp of the items
117
	 * @param items
118
	 * @return
119
	 */
120
	private double getMinMRP(List<Item> items){
121
        double minPrice = Double.MAX_VALUE;
122
        for(Item item: items){
123
            if(minPrice > item.getMrp()){
124
                minPrice =  item.getMrp();
125
            }
126
        }
127
        return minPrice;
128
    }
129
 
130
 
131
 
132
	/**
2367 rajveer 133
	 * Get the minimum price of the items
134
	 * @param items
135
	 * @return
136
	 */
137
	private double getMinPrice(List<Item> items){
138
        double minPrice = Double.MAX_VALUE;
5612 amit.gupta 139
        Item it = null;
2367 rajveer 140
        for(Item item: items){
141
            if(minPrice > item.getSellingPrice()){
142
                minPrice = item.getSellingPrice();
5612 amit.gupta 143
                it = item;
2367 rajveer 144
            }
145
        }
5612 amit.gupta 146
        if(it != null && voucherEntities.contains(it.getCatalogItemId())) {
147
    		try {
148
				cc = new CatalogClient().getClient();
149
				List<VoucherItemMapping> mapping;
150
				mapping = cc.getAllItemVouchers(it.getId());
151
				for (VoucherItemMapping vim : mapping) {
152
					minPrice = minPrice - vim.getAmount();
153
				}
154
			} catch (Exception e) {
155
				// TODO Auto-generated catch block
156
				e.printStackTrace();
157
			}
158
        }
2367 rajveer 159
        return minPrice;
160
    }
161
 
162
	/**
163
	 * Check whether product is mobile or not
164
	 * @param item
165
	 * @return
166
	 */
167
	private boolean isMobile(Item item){
4802 amit.gupta 168
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
169
		return parentCategory.getID() == Utils.MOBILE_PHONES_CATAGORY;
2367 rajveer 170
	}
171
 
172
	/**
5229 varun.gupt 173
	 * Checks whether a product is tablet or not
174
	 */
175
	private boolean isTablet(Item item) {
176
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
177
		return parentCategory.getID() == Utils.TABLETS_CATEGORY;
178
	}
5935 amit.gupta 179
 
180
	/**
181
	 * Checks whether a product is camera or not
182
	 */
183
	private boolean isCamera(Item item) {
184
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
185
		return parentCategory.getID() == Utils.CAMERAS_CATEGORY;
186
	}
5229 varun.gupt 187
 
188
	/**
4143 varun.gupt 189
	 * Checks whether a product is laptop or not
190
	 */
191
	private boolean isLaptop(Item item) {
4802 amit.gupta 192
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
193
		return parentCategory.getID() == Utils.LAPTOPS_CATEGORY;
4143 varun.gupt 194
	}
195
 
196
	/**
5355 varun.gupt 197
	 * Checks whether a product is accessory or not
198
	 */
199
	private boolean isAccessory(Item item)	{
200
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
201
		return parentCategory.getID() == Utils.MOBILE_ACCESSORIES_CATEGORY || parentCategory.getID() == Utils.LAPTOP_ACCESSORIES_CATEGORY;
202
	}
203
 
204
	/**
2367 rajveer 205
	 * 
206
	 * @param item
207
	 * @return
208
	 */
209
	private String getProductTitle(Item item){
2542 rajveer 210
		String title = ((item.getBrand() != null) ? item.getBrand().trim() + " " : "")
211
		+ ((item.getModelName() != null) ? item.getModelName().trim() + " " : "")
212
		+ (( item.getModelNumber() != null ) ? item.getModelNumber().trim() : "" );
2561 rajveer 213
		title = title.replaceAll("  ", " ");
2367 rajveer 214
		return title;
215
	}
216
 
217
	/**
1678 rajveer 218
	 * get xml feed for partner sites
219
	 * @param irDataXMLSnippets
220
	 * @throws Exception
221
	 */
2367 rajveer 222
	private void getProductsXML(ArrayList<String> irDataXMLSnippets) throws Exception{
5113 amit.gupta 223
		LogisticsService.Client prod_client = null;
5350 varun.gupt 224
		Map<Long, ItemCouponDiscount> couponsAndDiscounts = new HashMap<Long, ItemCouponDiscount>();
225
 
5113 amit.gupta 226
		try {
227
			LogisticsClient logistics_prod = new LogisticsClient("logistics_service_prod_server_host","logistics_service_prod_server_port");
228
			prod_client = logistics_prod.getClient();
5350 varun.gupt 229
 
230
			List<Long> itemIds = new ArrayList<Long>();
231
 
232
			for(Long entityId: entityIdItemMap.keySet()){
233
 
234
				List<Item> items = entityIdItemMap.get(entityId);
235
				Item firstItem = items.get(0);
236
 
237
				if(isMobile(firstItem) || isLaptop(firstItem)) {
238
					itemIds.add(firstItem.getId());
239
				}
240
			}
241
 
242
			PromotionClient promotionClient = new PromotionClient();
243
			in.shop2020.model.v1.user.PromotionService.Client promotionServiceClient = promotionClient.getClient();
244
 
245
			List<ItemCouponDiscount> itemsCouponsAndDiscounts = promotionServiceClient.getItemDiscountMap(itemIds);
246
 
247
			for (ItemCouponDiscount itemCouponDiscount: itemsCouponsAndDiscounts) {
248
				couponsAndDiscounts.put(itemCouponDiscount.getItemId(), itemCouponDiscount);
249
			}
250
 
5113 amit.gupta 251
		} catch (Exception e) {
252
			prod_client = null;
5350 varun.gupt 253
			Utils.info("Logistics estimations can't be fetched as Logistics Service is inaccessible" + e);
5113 amit.gupta 254
		}
5350 varun.gupt 255
 
2367 rajveer 256
		for(Long entityId: entityIdItemMap.keySet()){
257
			List<Item> items = entityIdItemMap.get(entityId);
258
			Item firstItem = items.get(0);
5229 varun.gupt 259
 
260
			if(!isMobile(firstItem) && !isTablet(firstItem))	{
1678 rajveer 261
				continue;
262
			}
263
 
264
			irDataXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
265
 
2367 rajveer 266
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
1678 rajveer 267
 
2367 rajveer 268
			String title = getProductTitle(firstItem);
1678 rajveer 269
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + title + "</ProductName>");
270
 
2367 rajveer 271
			String url = getProductURL(entityId, firstItem);
3929 mandeep.dh 272
 
273
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator +
274
			                  "website" + File.separator + entityId + File.separator + "icon.jpg";
275
 
1678 rajveer 276
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + url + "</ProductURL>");
6025 amit.gupta 277
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<Availability>" + (catalogItemIds.contains(entityId) ? "Y" : "N") + "</Availability>");
5350 varun.gupt 278
			double minPrice = getMinPrice(items);
1678 rajveer 279
 
5350 varun.gupt 280
			if(couponsAndDiscounts.containsKey(firstItem.getId()))	{
281
 
282
				int discountedPrice = (int)(minPrice - couponsAndDiscounts.get(firstItem.getId()).getDiscount());
283
				irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + discountedPrice + "</ProductPrice>");
284
 
285
			} else	{
286
				irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + minPrice + "</ProductPrice>");
287
			}
288
 
3964 rajveer 289
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + getMinMRP(items) + "</ProductMRP>");
290
 
5113 amit.gupta 291
			LogisticsInfo logisticsInfo = null;
292
			if(prod_client != null){
293
				try {
294
					Long itemId = prod_client.getEntityLogisticsEstimation(
295
							entityId, DEFAULT_PINCODE, DeliveryType.PREPAID)
296
							.get(0);
297
					logisticsInfo = prod_client.getLogisticsEstimation(itemId,
298
							DEFAULT_PINCODE, DeliveryType.PREPAID);
299
					irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductDeliveryEstimate>" + logisticsInfo.getDeliveryTime() + "</ProductDeliveryEstimate>");
300
				} catch (Exception e1) {
301
					Utils.info("Unable to get Estimation for Entity: " + entityId + "\n" + e1);
302
				}
303
			}
2130 rajveer 304
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
305
 
1678 rajveer 306
			irDataXMLSnippets.add(this.xmlIndentation[1] + "</products>");		
307
		}
308
	}
309
 
310
	/**
311
	 * Generate the xml list of all the active phones and store in a file
312
	 * @throws Exception
313
	 */
2227 rajveer 314
	public void generateProductsListXML() throws Exception {
1678 rajveer 315
		ArrayList<String> productXMLSnippets = new ArrayList<String>();
316
		productXMLSnippets.add("<saholic.com>");
317
 
318
		getProductsXML(productXMLSnippets);
319
 
320
		productXMLSnippets.add("</saholic.com>");
321
 
322
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
323
 
324
		Utils.info(productDataXML);
325
 
326
		// Write it to file
2130 rajveer 327
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicmobilephones.xml";
1678 rajveer 328
		DBUtils.store(productDataXML, productXMLFilename);
329
	}
2227 rajveer 330
 
5355 varun.gupt 331
	/**
332
	 * Generate the xml list of all the active accessories and store in a file
333
	 * @throws Exception
334
	 */
335
	public void generateAccessoriesXML() throws Exception	{
336
		LogisticsService.Client prod_client = null;
337
 
338
		try	{
339
			LogisticsClient logistics_prod = new LogisticsClient("logistics_service_prod_server_host","logistics_service_prod_server_port");
340
			prod_client = logistics_prod.getClient();
341
 
342
		} catch (Exception e) {
343
			prod_client = null;
344
			Utils.info("Logistics estimations can't be fetched as Logistics Service is inaccessible" + e);
345
		}
346
		List<String> accessoriesXMLSnippets = new ArrayList<String>();
347
 
348
		accessoriesXMLSnippets.add("<saholic.com>");
349
 
350
		for(Long entityId: entityIdItemMap.keySet())	{
351
 
352
			List<Item> items = entityIdItemMap.get(entityId);
353
			Item firstItem = items.get(0);
354
 
355
			if(! isAccessory(firstItem))	{
356
				continue;
357
			}
358
			String title = getProductTitle(firstItem);
359
			String url = getProductURL(entityId, firstItem);
360
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator +
361
            "website" + File.separator + entityId + File.separator + "icon.jpg";
362
 
363
			accessoriesXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
364
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
5362 varun.gupt 365
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + StringEscapeUtils.escapeXml(title) + "</ProductName>");
5363 varun.gupt 366
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + StringEscapeUtils.escapeXml(url) + "</ProductURL>");
5355 varun.gupt 367
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + getMinPrice(items) + "</ProductPrice>");
368
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + getMinMRP(items) + "</ProductMRP>");
369
 
370
			LogisticsInfo logisticsInfo = null;
371
			if(prod_client != null){
372
				try {
373
					Long itemId = prod_client.getEntityLogisticsEstimation(entityId, DEFAULT_PINCODE, DeliveryType.PREPAID).get(0);
374
					logisticsInfo = prod_client.getLogisticsEstimation(itemId, DEFAULT_PINCODE, DeliveryType.PREPAID);
375
					accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductDeliveryEstimate>" + logisticsInfo.getDeliveryTime() + "</ProductDeliveryEstimate>");
376
				} catch (Exception e1) {
377
					Utils.info("Unable to get Estimation for Entity: " + entityId + "\n" + e1);
378
				}
379
			}
380
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
381
			accessoriesXMLSnippets.add(this.xmlIndentation[1] + "</products>");		
382
		}
383
 
384
		accessoriesXMLSnippets.add("</saholic.com>");
2227 rajveer 385
 
5355 varun.gupt 386
		String accessoriesXML = StringUtils.join(accessoriesXMLSnippets, "\n");
387
 
388
		Utils.info(accessoriesXML);
389
 
390
		// Write it to file
391
		String accessoriesXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicaccessories.xml";
392
		DBUtils.store(accessoriesXML, accessoriesXMLFilename);
393
	}
2227 rajveer 394
 
5935 amit.gupta 395
 
396
 
2227 rajveer 397
	/**
5935 amit.gupta 398
	 * Generate the xml list of all the active cameras and store in a file
399
	 * @throws Exception
400
	 */
401
	public void generateCamerasXML() throws Exception	{
402
		LogisticsService.Client prod_client = null;
403
 
404
		try	{
405
			LogisticsClient logistics_prod = new LogisticsClient("logistics_service_prod_server_host","logistics_service_prod_server_port");
406
			prod_client = logistics_prod.getClient();
407
 
408
		} catch (Exception e) {
409
			prod_client = null;
410
			Utils.info("Logistics estimations can't be fetched as Logistics Service is inaccessible" + e);
411
		}
412
		List<String> camerasXMLSnippets = new ArrayList<String>();
413
 
414
		camerasXMLSnippets.add("<saholic.com>");
415
 
416
		for(Long entityId: entityIdItemMap.keySet())	{
417
 
418
			List<Item> items = entityIdItemMap.get(entityId);
419
			Item firstItem = items.get(0);
420
 
421
			if(! isCamera(firstItem))	{
422
				continue;
423
			}
424
			String title = getProductTitle(firstItem);
425
			String url = getProductURL(entityId, firstItem);
426
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator +
427
			"website" + File.separator + entityId + File.separator + "icon.jpg";
428
 
429
			camerasXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
430
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
431
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + StringEscapeUtils.escapeXml(title) + "</ProductName>");
432
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + StringEscapeUtils.escapeXml(url) + "</ProductURL>");
433
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + getMinPrice(items) + "</ProductPrice>");
434
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + getMinMRP(items) + "</ProductMRP>");
6025 amit.gupta 435
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<Availability>" + (catalogItemIds.contains(entityId) ? "Y" : "N") + "</Availability>");
5935 amit.gupta 436
 
437
			LogisticsInfo logisticsInfo = null;
438
			if(prod_client != null){
439
				try {
440
					Long itemId = prod_client.getEntityLogisticsEstimation(entityId, DEFAULT_PINCODE, DeliveryType.PREPAID).get(0);
441
					logisticsInfo = prod_client.getLogisticsEstimation(itemId, DEFAULT_PINCODE, DeliveryType.PREPAID);
442
					camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductDeliveryEstimate>" + logisticsInfo.getDeliveryTime() + "</ProductDeliveryEstimate>");
443
				} catch (Exception e1) {
444
					Utils.info("Unable to get Estimation for Entity: " + entityId + "\n" + e1);
445
				}
446
			}
447
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
448
			camerasXMLSnippets.add(this.xmlIndentation[1] + "</products>");		
449
		}
450
 
451
		camerasXMLSnippets.add("</saholic.com>");
452
 
453
		String camerasXML = StringUtils.join(camerasXMLSnippets, "\n");
454
 
455
		Utils.info(camerasXML);
456
 
457
		// Write it to file
458
		String accessoriesXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholiccameras.xml";
459
		DBUtils.store(camerasXML, accessoriesXMLFilename);
460
	}
461
 
462
	/**
2227 rajveer 463
	 * get xml feed for partner sites
464
	 * @param irDataXMLSnippets
465
	 * @throws Exception
466
	 */
467
	private void getProductsJavascript(StringBuffer sb) throws Exception{
4143 varun.gupt 468
 
5347 amit.gupta 469
		Map<String, Map<String, Long>> products = new HashMap<String, Map<String,Long>>();
2367 rajveer 470
 
5347 amit.gupta 471
		for(Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet())	{
472
			Item item = entry.getValue().get(0);
5930 amit.gupta 473
			in.shop2020.metamodel.definitions.Category category = defContainer.getCategory(item.getCategory());
474
			in.shop2020.metamodel.definitions.Category parentCategory = category.getParentCategory();
475
			String categoryLabel = category.getLabel();
5347 amit.gupta 476
			if(parentCategory.isComparable()){
5930 amit.gupta 477
				categoryLabel = parentCategory.getLabel();
2227 rajveer 478
			}
5930 amit.gupta 479
			if(!products.containsKey(categoryLabel)){
480
				Map<String, Long> catMap = new HashMap<String, Long>();
481
				products.put(categoryLabel, catMap);
482
			}
483
			products.get(categoryLabel).put(getProductTitle(item), entry.getKey());
2227 rajveer 484
		}
4143 varun.gupt 485
		sb.append(new JSONObject(products));
2227 rajveer 486
	}
487
 
488
 
489
	/**
490
	 * Generate the javascript list of all the active phones and store in a file
491
	 * @throws Exception
492
	 */
493
	public void generateProductListJavascript() throws Exception {
494
		StringBuffer productsJavascript = new StringBuffer();
495
 
4143 varun.gupt 496
		productsJavascript.append("var productIdNames=");
2227 rajveer 497
 
498
		getProductsJavascript(productsJavascript);
499
 
4143 varun.gupt 500
		productsJavascript.append(";");
2227 rajveer 501
 
502
		// Write it to file
503
		String productXMLFilename = Utils.EXPORT_JAVASCRIPT_CONTENT_PATH + "saholicmobilephones.js";
504
		DBUtils.store(productsJavascript.toString(), productXMLFilename);
505
	}
4188 varun.gupt 506
 
507
    private void populateEntityIdItemMap(List<Item> items){
508
        Date toDate = new Date();
509
        for(Item item: items){
510
            //TODO Can be removed as we are checking in calling function
511
            if(!(item.getItemStatus()==status.ACTIVE || item.getItemStatus()==status.CONTENT_COMPLETE || item.getItemStatus() == status.PAUSED)){
512
                continue;
513
            }
514
            if(toDate.getTime() < item.getStartDate() ||  item.getSellingPrice() == 0){
515
                continue;
516
            }
517
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
518
            if(itemList == null){
519
                itemList = new ArrayList<Item>();
520
            }
521
            itemList.add(item);
522
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
523
        }
524
 
525
        //Remove all items which have not been updated since last content generation.
526
        List<Long> removeEntities = new ArrayList<Long>();
527
        for(Long entityId:entityIdItemMap.keySet()){
528
            boolean isValidEntity = false;
529
            //If any one of the items has been updated before current timestamp, than we generate content for whole entity
530
            for(Item item: entityIdItemMap.get(entityId)){
531
                if(item.getUpdatedOn() > 0){
532
                    isValidEntity = true;
533
                }
534
            }
535
            if(!isValidEntity){
536
                removeEntities.add(entityId);
537
            }
538
        }
539
        for(Long entityId: removeEntities){
540
            entityIdItemMap.remove(entityId);
541
        }
542
    }
5229 varun.gupt 543
 
544
    /**
545
     * Generate XML feed for mobile site
546
     * @throws Exception
547
     */
548
    public void generateXMLFeedForMobileSite() throws Exception	{
549
    	List<String> productXMLSnippets = new ArrayList<String>();
550
		productXMLSnippets.add("<Products>");
551
		List<Long> itemIds = new ArrayList<Long>();
552
 
553
		for(Long entityId: entityIdItemMap.keySet()){
554
			List<Item> items = entityIdItemMap.get(entityId);
555
			Item firstItem = items.get(0);
556
			Utils.info("first Item: " + firstItem);
557
 
558
			if(isMobile(firstItem) || isLaptop(firstItem)) {
559
				itemIds.add(firstItem.getId());
560
			}
561
		}
4188 varun.gupt 562
 
5229 varun.gupt 563
		List<String> descriptions = new ArrayList<String>();
564
		descriptions.add("8MP camera, Super AMOLED Plus display, Android Gingerbread");
565
		descriptions.add("Android OS v2.2 Froyo, 800MHz processor, 3.5\" capacitive display");
566
		descriptions.add("Dual-SIM, Wi-Fi, Bluetooth, Social networking &amp; IM");
567
		descriptions.add("Android Gingerbread, Facebook button, 5MP camera");
568
		descriptions.add("Android Gingerbread, 1GHz processor, 3.7\" Gorilla Glass display");
569
		descriptions.add("2GB RAM, 500GB HDD, Intel Core 2 Duo T6570 processor, DOS");
570
		descriptions.add("4GB RAM, 500GB HDD, Intel Core i5 2410M processor, Windows 7 Basic");
571
		descriptions.add("3.2\" touchscreen, 2MP camera, IM &amp; social networking");
572
 
573
		for(Long entityId: entityIdItemMap.keySet()) {
574
			List<Item> items = entityIdItemMap.get(entityId);
575
			Item firstItem = items.get(0);
576
 
577
			if(!isMobile(firstItem) && !isLaptop(firstItem)){
578
				continue;
579
			}
4188 varun.gupt 580
 
5229 varun.gupt 581
			String url = getProductURL(entityId, firstItem);
582
			String imageUrl = "http://www.saholic.com/images/website" + File.separator + entityId + File.separator + "thumbnail.jpg";
583
			String description = descriptions.get((int) (8 * Math.random()));
584
			double minPrice = getMinPrice(items);
585
 
586
			String productType = "";
587
 
588
			if (firstItem.getCategory() == 10001 || firstItem.getCategory() == 10002 || firstItem.getCategory() == 10003 || firstItem.getCategory() == 10004 || firstItem.getCategory() == 10005)	{
589
				productType = "Mobile Phone";
590
 
591
			} else if (firstItem.getCategory() == 10010)	{
592
				productType = "Tablet";
593
 
594
			} else if (firstItem.getCategory() == 10050)	{
595
				productType = "Laptop";
596
			}
597
 
598
			productXMLSnippets.add(this.xmlIndentation[1] + "<Product>");	
599
 
600
			productXMLSnippets.add(this.xmlIndentation[2] + "<ID>" + entityId + "</ID>");
601
			productXMLSnippets.add(this.xmlIndentation[2] + "<Type>" + productType + "</Type>");
602
			productXMLSnippets.add(this.xmlIndentation[2] + "<Brand>" + firstItem.getBrand() + "</Brand>");
603
			productXMLSnippets.add(this.xmlIndentation[2] + "<ModelName>" + firstItem.getModelName() + "</ModelName>");
604
			productXMLSnippets.add(this.xmlIndentation[2] + "<ModelNumber>" + firstItem.getModelNumber() + "</ModelNumber>");
605
			productXMLSnippets.add(this.xmlIndentation[2] + "<URL>" + url + "</URL>");
606
			productXMLSnippets.add(this.xmlIndentation[2] + "<ImageURL>" + imageUrl + "</ImageURL>");
607
			productXMLSnippets.add(this.xmlIndentation[2] + "<ShortDesc>" + description + "</ShortDesc>");
608
			productXMLSnippets.add(this.xmlIndentation[2] + "<MRP>" + firstItem.getMrp() + "</MRP>");
609
			productXMLSnippets.add(this.xmlIndentation[2] + "<SellingPrice>" + (int)minPrice  + "</SellingPrice>");
610
 
611
			productXMLSnippets.add(this.xmlIndentation[1] + "</Product>");
612
		}
613
 
614
		productXMLSnippets.add("</Products>");
615
 
616
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
617
 
618
		Utils.info(productDataXML);
619
 
620
		// Write it to file
621
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "msitedata.xml";
622
		DBUtils.store(productDataXML, productXMLFilename);
623
    }
624
 
4188 varun.gupt 625
	/**
626
	 * Generate the xml list of all the active phones and store in a file
627
	 * @throws Exception
628
	 */
629
	public void generateProductXMLForDisplayAds() throws Exception {
4384 varun.gupt 630
		Utils.info("Generating Product XML for display ads");
4188 varun.gupt 631
		List<String> productXMLSnippets = new ArrayList<String>();
632
		productXMLSnippets.add("<saholic.com>");
633
		List<Long> itemIds = new ArrayList<Long>();
4384 varun.gupt 634
 
635
		Utils.info("Entity Ids: " + entityIdItemMap.keySet());
4188 varun.gupt 636
 
637
		for(Long entityId: entityIdItemMap.keySet()){
638
			List<Item> items = entityIdItemMap.get(entityId);
639
			Item firstItem = items.get(0);
4384 varun.gupt 640
			Utils.info("first Item: " + firstItem);
641
 
4383 varun.gupt 642
			if(isMobile(firstItem) || isLaptop(firstItem)) {
4188 varun.gupt 643
				itemIds.add(firstItem.getId());
644
			}
645
		}
646
 
647
		PromotionClient promotionClient = new PromotionClient();
648
		in.shop2020.model.v1.user.PromotionService.Client promotionServiceClient = promotionClient.getClient();
649
 
650
		List<ItemCouponDiscount> itemsCouponsAndDiscounts = promotionServiceClient.getItemDiscountMap(itemIds);
651
 
652
		Map<Long, ItemCouponDiscount> couponsAndDiscounts = new HashMap<Long, ItemCouponDiscount>();
653
 
654
		for (ItemCouponDiscount itemCouponDiscount: itemsCouponsAndDiscounts) {
655
			couponsAndDiscounts.put(itemCouponDiscount.getItemId(), itemCouponDiscount);
656
		}
4384 varun.gupt 657
		Utils.info("Entity IDs: " + entityIdItemMap.keySet());
4188 varun.gupt 658
 
659
		for(Long entityId: entityIdItemMap.keySet()) {
660
			List<Item> items = entityIdItemMap.get(entityId);
661
			Item firstItem = items.get(0);
4384 varun.gupt 662
 
663
			Utils.info("First Item: " + firstItem);
664
 
4382 varun.gupt 665
			if(!isMobile(firstItem) && !isLaptop(firstItem)){
4188 varun.gupt 666
				continue;
667
			}
668
 
669
			productXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
670
 
671
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
672
 
673
			String title = getProductTitle(firstItem);
674
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + title + "</ProductName>");
675
 
676
			String url = getProductURL(entityId, firstItem);
677
 
678
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator + entityId + File.separator + "icon.jpg";    
679
 
680
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + url + "</ProductURL>");
681
 
682
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
683
 
684
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + firstItem.getMrp() + "</ProductMRP>");
685
 
686
			double minPrice = getMinPrice(items);
687
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductSellingPrice>" + (int)minPrice  + "</ProductSellingPrice>");
6025 amit.gupta 688
			productXMLSnippets.add(this.xmlIndentation[2] + "<Availability>" + (catalogItemIds.contains(entityId) ? "Y" : "N") + "</Availability>");
4188 varun.gupt 689
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductDiscount>" + (int)((firstItem.getMrp()-minPrice)/firstItem.getMrp()*100) + "</ProductDiscount>");
690
 
691
			long itemId = firstItem.getId();
692
 
693
			if(couponsAndDiscounts.containsKey(itemId))	{
694
 
695
				ItemCouponDiscount itemCouponDiscount = couponsAndDiscounts.get(itemId);
696
 
697
				productXMLSnippets.add(this.xmlIndentation[2] + "<ProductCoupons>");
698
				productXMLSnippets.add(this.xmlIndentation[3] + "<Coupon>");
699
				productXMLSnippets.add(this.xmlIndentation[4] + "<CouponCode>" + itemCouponDiscount.getCouponCode() + "</CouponCode>");
700
				productXMLSnippets.add(this.xmlIndentation[4] + "<PriceAfterCoupon>" + (int)(minPrice - itemCouponDiscount.getDiscount()) + "</PriceAfterCoupon>");
701
				productXMLSnippets.add(this.xmlIndentation[3] + "</Coupon>");
702
				productXMLSnippets.add(this.xmlIndentation[2] + "</ProductCoupons>");
703
 
704
			} else	{
705
				productXMLSnippets.add(this.xmlIndentation[2] + "<ProductCoupons />");
706
			}
707
 
708
			String description = "";
709
			Entity entity = CreationUtils.getEntity(entityId);
710
			if(entity!=null){
711
				if(entity.getSlide(130001) !=null){
4202 varun.gupt 712
					description = StringEscapeUtils.escapeXml(entity.getSlide(130001).getFreeformContent().getFreeformText());
4188 varun.gupt 713
				}
714
			}
715
 
716
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductDescription>" + description + "</ProductDescription>");
717
 
718
			productXMLSnippets.add(this.xmlIndentation[1] + "</products>");	
719
		}
720
 
721
		productXMLSnippets.add("</saholic.com>");
722
 
723
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
724
 
725
		Utils.info(productDataXML);
726
 
727
		// Write it to file
728
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "advertismentapi.xml";
729
		DBUtils.store(productDataXML, productXMLFilename);
730
	}
5229 varun.gupt 731
 
732
	public static void main(String[] args) throws Exception {
733
		CatalogClient cl = new CatalogClient();
5945 mandeep.dh 734
		in.shop2020.model.v1.catalog.CatalogService.Client client = cl.getClient();
5229 varun.gupt 735
 
5612 amit.gupta 736
//		List<Item> items = cl.getClient().getAllItemsByStatus(status.ACTIVE);
737
		List<Long> items1 = Arrays.asList(1587l,2222l,2258l,2270l,5836l,6718l, 6719l);
738
		List<Item> items = new ArrayList<Item>();
739
		for (Long l : items1) {
740
			items.add(cl.getClient().getItem(l));
741
		}
742
		//items.addAll(cl.getClient().getAllItemsByStatus(status.PAUSED));
5229 varun.gupt 743
//		items.addAll(cl.getClient().getAllItemsByStatus(status.PAUSED_BY_RISK));
744
 
745
		Map<Long, List<Item>> entityIdItemMap1 = new HashMap<Long, List<Item>>();
746
		ProductListGenerator pl = new ProductListGenerator(entityIdItemMap1);
6025 amit.gupta 747
		//pl.generateThinkDigitFeed();
5229 varun.gupt 748
		pl.populateEntityIdItemMap(items);
5612 amit.gupta 749
		//pl.generateAccessoriesXML();
6025 amit.gupta 750
		//pl.generateXMLFeedForMobileSite();
5229 varun.gupt 751
	}
5612 amit.gupta 752
 
753
    private String readFile(String path) throws IOException {
754
		FileInputStream stream = new FileInputStream(new File(path));
755
		try {
756
			FileChannel fc = stream.getChannel();
757
			MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()-1);
758
			/* Instead of using default, pass in a decoder. */
759
			return Charset.defaultCharset().decode(bb).toString();
760
		}
761
		finally {
762
			stream.close();
763
		}
764
	}
6025 amit.gupta 765
    /**
766
     * Feed generated for thinkdigit that only contains the live items
767
     * feed should have s
768
     */
769
    public void generateThinkDigitFeed() throws Exception{
770
 
771
    	List<String> productXMLSnippets = new ArrayList<String>();
772
    	productXMLSnippets.add("<root>");
773
    	String thinkDigitFeedFileName = Utils.EXPORT_PARTNERS_CONTENT_PATH + "all-categories.xml";
774
    	cc = new CatalogClient().getClient();
775
    	List<Item> items = cc.getAllItemsByStatus(status.ACTIVE);
776
    	Client catalogClientProd = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(), ConfigClientKeys.catalog_service_server_port.toString()).getClient();
777
    	for (Item item : items){
778
    		Category parentCategory = Catalog.getInstance().getDefinitionsContainer().getCategory(item.getCategory()).getParentCategory(); 
779
    		boolean isActive = true;
780
    		if(validParentCategories.contains(parentCategory.getID()) && !catalogItemIds.contains(item.getCatalogItemId())) {
781
    			if(item.isRisky()){
782
    				try {
783
    					ItemShippingInfo isi = catalogClientProd.isActive(item.getId());
784
    					isActive = isi.isIsActive();
785
    				} catch (Exception e) {
786
    					isActive = true;
787
    				}
788
    			}
789
    			if(isActive) {
790
	    			productXMLSnippets.add(this.xmlIndentation[1] + "<products>");
791
	    			productXMLSnippets.add(this.xmlIndentation[2] + "<id>" + item.getCatalogItemId() + "</id>");
792
	    			productXMLSnippets.add(this.xmlIndentation[2] + "<product>" + getProductTitle(item) + "</product>");
6040 amit.gupta 793
	    			productXMLSnippets.add(this.xmlIndentation[2] + "<Product_URL>" + getProductURL(item.getCatalogItemId(), item, 59) + "</Product_URL>");
6025 amit.gupta 794
	    			productXMLSnippets.add(this.xmlIndentation[2] + "<Product_Price>" + (int)item.getSellingPrice() + "</Product_Price>");
795
	    			productXMLSnippets.add(this.xmlIndentation[2] + "<Merchant_Name>" + "saholic.com" + "</Merchant_Name>");
796
	    			productXMLSnippets.add(this.xmlIndentation[2] + "<Category_Name>" + parentCategory.getLabel() + "</Category_Name>");
797
	    			productXMLSnippets.add(this.xmlIndentation[1] + "</products>");
798
	    			catalogItemIds.add(item.getCatalogItemId());
799
    			}
800
    		}
801
    	}
802
    	productXMLSnippets.add("</root>");
803
    	String productDataXML = StringUtils.join(productXMLSnippets, "\n");
804
    	DBUtils.store(productDataXML, thinkDigitFeedFileName);
805
 
806
    }
6257 rajveer 807
 
808
    public static void updatePriceForEntity(long catalogItemId, double sp, double mrp){
809
    	try{
810
    		String filename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicmobilephones.xml";
811
    		File file = new File(filename);
812
    		if (file.exists()){
813
    			DOMParser parser = new DOMParser();
814
    			parser.parse(filename);
815
    			Document doc = parser.getDocument();
816
    			NodeList list = doc.getElementsByTagName("ProductSKU");
817
    			for(int i=0; i<list.getLength(); i++){
818
    				if(list.item(i).getTextContent().equals(catalogItemId+"")){
819
    					Node spNode = doc.getElementsByTagName("ProductPrice").item(i);
820
    					spNode.setTextContent(sp+"");
821
    					Node mrpNode = doc.getElementsByTagName("ProductMRP").item(i);
822
    					mrpNode.setTextContent(mrp+"");
823
    				}
824
    			}
825
    			writeXmlFile(doc, filename);
826
    		}
827
    		else{
828
    			System.out.println("File not found!");
829
    		}
830
    	}
831
    	catch (Exception e){
832
    		e.getMessage();
833
    	}
834
    }
835
 
836
    // This method writes a DOM document to a file
837
    public static void writeXmlFile(Document doc, String filename) {
838
    	try {
839
    		// Prepare the DOM document for writing
840
    		Source source = new DOMSource(doc);
841
 
842
    		// Prepare the output file
843
    		File file = new File(filename);
844
    		Result result = new StreamResult(file);
845
 
846
    		// Write the DOM document to the file
847
    		Transformer xformer = TransformerFactory.newInstance().newTransformer();
848
    		xformer.transform(source, result);
849
    	} catch (TransformerConfigurationException e) {
850
    	} catch (TransformerException e) {
851
    	}
852
    }
4143 varun.gupt 853
}