Subversion Repositories SmartDukaan

Rev

Rev 2726 | Rev 2735 | 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.ui.util;
2
 
3
import in.shop2020.metamodel.core.Bullet;
4
import in.shop2020.metamodel.core.Entity;
5
import in.shop2020.metamodel.core.Feature;
6
import in.shop2020.metamodel.core.PrimitiveDataObject;
7
import in.shop2020.metamodel.definitions.Catalog;
8
import in.shop2020.metamodel.util.CreationUtils;
9
import in.shop2020.metamodel.util.ExpandedBullet;
10
import in.shop2020.metamodel.util.ExpandedEntity;
11
import in.shop2020.metamodel.util.ExpandedFeature;
12
import in.shop2020.metamodel.util.ExpandedSlide;
13
import in.shop2020.util.Utils;
14
 
15
import java.io.BufferedWriter;
16
import java.io.File;
17
import java.io.FileInputStream;
18
import java.io.FileOutputStream;
19
import java.io.IOException;
20
import java.io.InputStream;
21
import java.io.OutputStream;
22
import java.io.OutputStreamWriter;
2227 rajveer 23
import java.net.URLEncoder;
2171 rajveer 24
import java.text.DecimalFormat;
2433 rajveer 25
import java.util.ArrayList;
2171 rajveer 26
import java.util.HashMap;
27
import java.util.List;
28
import java.util.Map;
2433 rajveer 29
import java.util.Properties;
2171 rajveer 30
 
31
import org.apache.velocity.Template;
32
import org.apache.velocity.VelocityContext;
33
import org.apache.velocity.app.Velocity;
34
import org.apache.velocity.exception.ParseErrorException;
35
import org.apache.velocity.exception.ResourceNotFoundException;
2305 vikas 36
import org.json.JSONObject;
2171 rajveer 37
 
38
/**
2433 rajveer 39
 * Utility class to merge Java data objects with VTL scripts.
40
 * Also generates images and other required stuff for rendering content
2171 rajveer 41
 * 
42
 * @author rajveer
43
 *
44
 */
45
public class NewVUI {
46
	String contentVersion;  
47
 
48
	public NewVUI(Long contentVersion) throws Exception {
2367 rajveer 49
		this.contentVersion = contentVersion.toString();
2171 rajveer 50
	}
51
 
52
	/**
2433 rajveer 53
	 * Utility method to delete a directory.
54
	 * @param dir
55
	 * @return
2171 rajveer 56
	 */
2433 rajveer 57
	private boolean deleteDir(File dir) {
2171 rajveer 58
	    if (dir.isDirectory()) {
59
	        String[] children = dir.list();
60
	        for (int i=0; i<children.length; i++) {
61
	            boolean success = deleteDir(new File(dir, children[i]));
62
	            if (!success) {
63
	                return false;
64
	            }
65
	        }
66
	    }
67
	    // The directory is now empty so delete it
68
	    return dir.delete();
69
	}
70
 
2433 rajveer 71
	/**
72
	 * Delete old resources of the entity for which content needs to be regenerated  
73
	 * @param mediaPath
74
	 * @param contentPath
75
	 */
2171 rajveer 76
	private void deleteOldResources(String mediaPath, String contentPath) {
77
		File f = new File(contentPath);
78
		if(f.exists()){
79
			deleteDir(f);
80
		}
81
 
82
		f = new File(mediaPath);
83
		if(f.exists()){
84
			deleteDir(f);
85
		}
86
	}
87
 
2433 rajveer 88
	/**
89
	 * It Actually copies the images from some given directory to export directory.
90
	 * It also attaches the imagePrefix at the end of image name. 
91
	 * @param catalogId
92
	 * @param imagePrefix
93
	 * @throws IOException
94
	 */
2171 rajveer 95
	private void generateImages(long catalogId, String imagePrefix) throws IOException {
96
		String globalImageDirPath = Utils.CONTENT_DB_PATH + "media" + File.separator;
97
		String globalDefaultImagePath = globalImageDirPath + "default.jpg";
98
 
99
		String imageDirPath = globalImageDirPath + catalogId + File.separator;
100
		String defaultImagePath = imageDirPath + "default.jpg";
101
 
102
		/*
103
		 * Create the directory for this entity if it didn't exist.
104
		 */
105
		File f = new File(globalImageDirPath + catalogId);
106
		if (!f.exists()) {
107
			f.mkdir();
108
		}
109
 
110
		/*
111
		 * If the default image is not present for this entity, copy the global
112
		 * default image.
113
		 * TODO: This part will be moved to the Jython Script
114
		 */
115
		File f3 = new File(defaultImagePath);
116
		if (!f3.exists()) {
117
		        copyFile(globalDefaultImagePath, defaultImagePath);
118
		    }
119
 
120
		String exportPath = Utils.EXPORT_MEDIA_PATH + catalogId;
121
		/*
122
		 * Copying the generated content from db/media to export/media. This
123
		 * will also insert a timestamp tag in the file names.
124
		 */
125
		File sourceFile = new File(globalImageDirPath + catalogId);
126
		File destinationFile = new File(exportPath);
2198 rajveer 127
		copyDirectory(sourceFile, destinationFile, imagePrefix);
2171 rajveer 128
 
129
		/*
130
		 * Copy the thumbnail and the icon files. This is required so that we can display the
131
		 * thumbnail on the cart page and icon on the facebook.
132
		 */
2198 rajveer 133
		copyFile(imageDirPath + "thumbnail.jpg", exportPath + File.separator + "thumbnail.jpg");
134
		copyFile(imageDirPath + "icon.jpg", exportPath + File.separator + "icon.jpg");
2171 rajveer 135
		}
136
 
137
	/**
138
	 * Copies the contents of the input file into the output file. Creates the
139
	 * output file if it doesn't exist already.
140
	 * 
141
	 * @param inputFile
142
	 *            File to be copied.
143
	 * @param outputFile
144
	 *            File to be created.
145
	 * @throws IOException
146
	 */
147
	private void copyFile(String inputFile, String outputFile) throws IOException {
148
		File sourceFile = new File(inputFile);
149
		File destinationFile = new File(outputFile);
2206 rajveer 150
 
2171 rajveer 151
		if (!destinationFile.exists())
152
			destinationFile.createNewFile();
153
 
154
		InputStream in = new FileInputStream(sourceFile);
2305 vikas 155
	    OutputStream out = new FileOutputStream(destinationFile);
2171 rajveer 156
		// Copy the bits from instream to outstream
157
		byte[] buf = new byte[1024];
158
		int len;
159
		while ((len = in.read(buf)) > 0) {
160
			out.write(buf, 0, len);
161
		}
162
		in.close();
163
		out.close();
164
	}
165
 
2433 rajveer 166
 
167
	/**
168
	 * Copy the images from one directory to other. It also renames files while copying.
169
	 * If targetLocation does not exist, it will be created.
170
	 * @param sourceLocation
171
	 * @param targetLocation
172
	 * @param imagePrefix
173
	 * @throws IOException
174
	 */
2171 rajveer 175
	public void copyDirectory(File sourceLocation , File targetLocation, String imagePrefix) throws IOException {
176
 
177
	    if (sourceLocation.isDirectory()) {
178
	        if (!targetLocation.exists()) {
179
	            targetLocation.mkdir();
180
	        }
181
 
182
	        String[] children = sourceLocation.list();
183
	        for (int i=0; i<children.length; i++) {
184
	            copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), imagePrefix);
185
	        }
186
	    } else {
187
	        InputStream in = new FileInputStream(sourceLocation);
188
 
189
        	String fileName = targetLocation.getName().split("\\.")[0];
190
        	String fileExt = targetLocation.getName().split("\\.")[1];
191
        	String newFileName = targetLocation.getParent() + File.separator + imagePrefix + "-" + fileName + "-" + this.contentVersion + "." + fileExt; 
192
 
193
 
194
	        //String fileName = targetLocation
195
	        OutputStream out = new FileOutputStream(newFileName);
196
 
197
	        // Copy the bits from instream to outstream
198
	        byte[] buf = new byte[1024];
199
	        int len;
200
	        while ((len = in.read(buf)) > 0) {
201
	            out.write(buf, 0, len);
202
	        }
203
	        in.close();
204
	        out.close();
205
	    }
206
	}
207
 
2433 rajveer 208
	/**
209
	 * Get the commonly used product properties and store them in a file.  
210
	 * @param expEntity
211
	 * @param exportPath
212
	 */
2305 vikas 213
	private  void getProductPropertiesSnippet(ExpandedEntity expEntity, String exportPath) {
214
        long catalogId = expEntity.getID();
215
        try {
216
            expEntity = CreationUtils.getExpandedEntity(catalogId);
217
        } catch (Exception e) {
218
            e.printStackTrace();
219
        }
220
 
221
        String metaDescription = "";
222
        String metaKeywords = "";
223
        String entityUrl = getEntityURL(expEntity);
224
        String title = "";
225
 
226
        List<Feature>  features = expEntity.getSlide(130054).getFeatures();
227
        for(Feature feature: features){
228
            if(feature.getFeatureDefinitionID() == 120132){
229
                PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
230
                title = dataObject.getValue(); 
231
            }
232
            if(feature.getFeatureDefinitionID() == 120133){
233
                PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
234
                metaDescription = dataObject.getValue();
235
            }
236
            if(feature.getFeatureDefinitionID() == 120134){
237
                PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
238
                metaKeywords = dataObject.getValue();
239
            }
240
        }
2171 rajveer 241
 
2305 vikas 242
        try {
243
            JSONObject props = new JSONObject();
244
            props.put("metaDescription", metaDescription);
245
            props.put("metaKeywords", metaKeywords);
246
            props.put("entityUrl", entityUrl);
247
            props.put("title", title);
2433 rajveer 248
            props.put("name", getProductName(expEntity));
2651 rajveer 249
            if(expEntity.getCategory().getParentCategory().getID() != Utils.MOBILE_ACCESSORIES_CATEGORY){
250
            	props.put("displayAccessories", "TRUE");	
251
    		}else{
252
    			props.put("displayAccessories", "FALSE" );
253
    		}   
2433 rajveer 254
 
2651 rajveer 255
 
2305 vikas 256
            String exportFileName = exportPath + catalogId + File.separator
2367 rajveer 257
                    + "ProductPropertiesSnippet.vm";
2305 vikas 258
            File exportFile = new File(exportFileName);
259
            if (!exportFile.exists()) {
260
                exportFile.createNewFile();
261
            }
2171 rajveer 262
 
2305 vikas 263
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
264
                    new FileOutputStream(exportFile)));
265
 
266
            writer.write(props.toString());
267
 
268
            writer.flush();
269
            writer.close();
270
        } catch (Exception e) {
271
            e.printStackTrace();
272
        }
2171 rajveer 273
	}
2305 vikas 274
 
2433 rajveer 275
	/**
276
	 * Get slide names and write them in a file. This file will be used in comparison.
277
	 * @param expEntity
278
	 * @param exportPath
279
	 * @throws Exception
280
	 */
281
    private void getSlidenamesSnippet(ExpandedEntity expEntity, String exportPath) throws Exception{
2171 rajveer 282
	    long catalogId = expEntity.getID();
283
 
284
	    StringBuilder slideNames = new StringBuilder();
2433 rajveer 285
	    //TODO Investigate why brand + model number is used ?
2171 rajveer 286
	    slideNames.append(expEntity.getBrand() + " " + expEntity.getModelNumber() + " " + expEntity.getModelName() + "\n");
287
 
288
	    Map<Long, Double> slideScores = CreationUtils.getSlideComparisonScores(catalogId);
289
 
290
	    for(ExpandedSlide expSlide: expEntity.getExpandedSlides()){
291
	        if(expSlide.getSlideDefinitionID() == 130054){
292
	            continue;
293
	        }
294
	        slideNames.append(expSlide.getSlideDefinition().getLabel() + "!!!");
295
 
296
	        String bucketName = "None";
297
	        if(Catalog.getInstance().getDefinitionsContainer().getComparisonBucketName(expEntity.getCategoryID(), expSlide.getSlideDefinitionID()) != null){
298
	            bucketName = Catalog.getInstance().getDefinitionsContainer().getComparisonBucketName(expEntity.getCategoryID(), expSlide.getSlideDefinitionID());
299
	        }
300
	        slideNames.append(bucketName + "!!!");
301
 
302
	        double score = 0;
303
	        if(slideScores.get(expSlide.getSlideDefinitionID())!=null){
304
	            score = slideScores.get(expSlide.getSlideDefinitionID());
305
	        }
306
 
307
	        DecimalFormat oneDForm = new DecimalFormat("#.#");
308
	        score = Double.valueOf(oneDForm.format(score));
309
 
310
	        slideNames.append(score + "\n");
311
	    }
312
 
2367 rajveer 313
        String exportFileName = exportPath + catalogId + File.separator + "SlideNamesSnippet.vm";
2171 rajveer 314
        File exportFile = new File(exportFileName);
315
        if(!exportFile.exists()) {
316
            exportFile.createNewFile();
317
        }
318
 
319
        BufferedWriter writer = new BufferedWriter(
320
            new OutputStreamWriter(new FileOutputStream(exportFile)));
321
 
322
        writer.write(slideNames.toString());
323
        writer.flush();
324
        writer.close();
325
 
326
	}
2651 rajveer 327
 
2433 rajveer 328
 
2651 rajveer 329
	/**
330
	 * Get related accessories
331
	 * @param expEntity
332
	 * @param exportPath
333
	 * @throws Exception
334
	 */
335
    private void getRelatedAccessories(ExpandedEntity expEntity, String exportPath) throws Exception{
336
	    long catalogId = expEntity.getID();
337
 
338
	    Map<Long, List<Long>> relatedAccessories = CreationUtils.getRelatedAccessories().get(catalogId);
339
	    List<Long> priorityList = new ArrayList<Long>();
340
	    int individualLimit = 3;
341
	    int totalLimit = 10;
342
	    priorityList.add(Utils.CARRYING_CASE);
343
	    priorityList.add(Utils.SCREEN_GUARD);
344
	    priorityList.add(Utils.BATTERY);
345
	    priorityList.add(Utils.MEMORY_CARD);
346
	    priorityList.add(Utils.BLUETOOTH_HEADSET);
347
	    priorityList.add(Utils.HEADSET);
348
	    priorityList.add(Utils.CHARGER);
349
 
350
	    StringBuffer sb = new StringBuffer();
351
	    int totalCount = 0;
352
	    for(Long catID: priorityList){
353
	    	int individualCount = 0;
354
	    	List<Long> ents = relatedAccessories.get(catID);
355
	    	if(ents != null && !ents.isEmpty()){
356
	    		if(ents.size()>individualLimit){
357
	    			ents = ents.subList(0, individualLimit);
358
	    		}
359
	    		for(Long entID: ents){
360
	    			if(totalLimit > totalCount){
361
	    				sb.append(entID + "\n");
362
	    				individualCount++;
363
	    				totalCount++;
364
	    			}
365
	    		}
366
	    	}
367
	    }
368
 
369
        String exportFileName = exportPath + catalogId + File.separator + "RelatedAccessories.vm";
370
        File exportFile = new File(exportFileName);
371
        if(!exportFile.exists()) {
372
            exportFile.createNewFile();
373
        }
374
 
375
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportFile)));
376
 
377
        writer.write(sb.toString());
378
        writer.flush();
379
        writer.close();
380
 
381
	}
2733 rajveer 382
 
2651 rajveer 383
 
2433 rajveer 384
    /**
2733 rajveer 385
	 * Get most compared phones
386
	 * @param expEntity
387
	 * @param exportPath
388
	 * @throws Exception
389
	 */
390
    private void getMostComparedProducts(ExpandedEntity expEntity, String exportPath) throws Exception{
391
	    long catalogId = expEntity.getID();
392
 
393
	    Map<Long, Long> comparedPhones = CreationUtils.getComparisonStats().get(catalogId);
394
	    StringBuffer sb = new StringBuffer();
395
	    int maxCount = 10;
396
	    int count = 0;
397
	    for(Long entityID: comparedPhones.keySet()){
398
	    	if(count > maxCount){
399
				break;
400
			}
401
			sb.append(entityID + "\n");
402
			count++;
403
	    }
404
 
405
        String exportFileName = exportPath + catalogId + File.separator + "MostComparedProducts.vm";
406
        File exportFile = new File(exportFileName);
407
        if(!exportFile.exists()) {
408
            exportFile.createNewFile();
409
        }
410
 
411
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportFile)));
412
 
413
        writer.write(sb.toString());
414
        writer.flush();
415
        writer.close();
416
 
417
	}
418
 
419
    /**
2433 rajveer 420
     * Get the name of the product from entity. It considers null values also
421
     * @param expEntity
422
     * @return
423
     */
2726 rajveer 424
	public static String getProductName(ExpandedEntity expEntity){
2433 rajveer 425
		//FIXME Use stringbuilder
426
		String productName = ((expEntity.getBrand() != null) ? expEntity.getBrand().trim() + " " : "")
427
		+ ((expEntity.getModelName() != null) ? expEntity.getModelName().trim() + " " : "")
428
		+ (( expEntity.getModelNumber() != null ) ? expEntity.getModelNumber().trim() : "" );	
429
		return productName;
2171 rajveer 430
	}
431
 
2433 rajveer 432
	/**
433
	 * Get url of the entity. 
434
	 * @param expEntity
435
	 * @return
436
	 */
2171 rajveer 437
	private String getEntityURL(ExpandedEntity expEntity){
438
		String url = "/" + expEntity.getCategory().getParentCategory().getLabel().toLowerCase().replace(' ', '-') + "/";
2459 rajveer 439
		if(expEntity.getCategory().getParentCategory().getID() == Utils.ROOT_CATAGOEY){
440
			url = "/" + expEntity.getCategory().getLabel().toLowerCase().replace(' ', '-') + "/";
441
		}
442
 
2433 rajveer 443
		String productName = getProductName(expEntity);
444
		String productUrl = productName.toLowerCase().replace(' ', '-') + "-" + expEntity.getID();
2171 rajveer 445
		productUrl = productUrl.replaceAll("/", "-");
446
		url = url + productUrl;
2305 vikas 447
		url = url.replaceAll("-+", "-");
2171 rajveer 448
		return url;
449
	}
450
 
2433 rajveer 451
	/**
452
	 * get image prefix
453
	 * @param expEntity
454
	 * @return
455
	 */
2171 rajveer 456
	private String getImagePrefix(ExpandedEntity expEntity){
2433 rajveer 457
		String productName = getProductName(expEntity);
458
		String imagePrefix = productName.toLowerCase().replace(' ', '-');
2171 rajveer 459
		imagePrefix = imagePrefix.replaceAll("/", "-");
2367 rajveer 460
		imagePrefix = imagePrefix.replaceAll("-+", "-");
2171 rajveer 461
		return imagePrefix;
462
	}
463
 
2433 rajveer 464
 
465
	/**
466
	 * Get the required parameters for generating velocity content.
467
	 * @param expEntity
468
	 * @return
469
	 * @throws Exception
470
	 */
471
	private Map<String, String> getEntityParameters(ExpandedEntity expEntity) throws Exception{
472
		Map<String,String> params = new HashMap<String, String>();
473
		String title = getProductName(expEntity);
474
		String brandName = expEntity.getBrand().trim();
475
		String productName =  ((expEntity.getModelName() != null) ? expEntity.getModelName().trim() + " " : "")
476
		+ ((expEntity.getModelNumber() != null) ? expEntity.getModelNumber().trim() : "");
477
 
478
		String prodName = title;
479
		if (expEntity.getModelName() != null && !expEntity.getModelName().isEmpty() && (expEntity.getBrand().equals("Samsung") || expEntity.getBrand().equals("Sony Ericsson"))) {
480
			prodName = expEntity.getBrand().trim() + " " + ((expEntity.getModelName() != null) ? expEntity.getModelName().trim() : "");
481
		}
482
		String categoryName = expEntity.getCategory().getLabel();
483
		String tagline = "";
484
		String warranty = "";
485
		String tinySnippet = "";
486
		List<Feature>  features = expEntity.getSlide(130054).getFeatures();
487
		for(Feature feature: features){
488
			if(feature.getFeatureDefinitionID() == 120084){
489
				PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
490
				tagline = dataObject.getValue(); 
2197 rajveer 491
			}
2433 rajveer 492
			if(feature.getFeatureDefinitionID() == 120125){
493
				ExpandedFeature expFeature = new ExpandedFeature(feature);
494
				ExpandedBullet expBullet =expFeature.getExpandedBullets().get(0);
495
				if(expBullet != null){
496
					warranty = expBullet.getValue() + " "+ expBullet.getUnit().getShortForm();
2171 rajveer 497
				}
498
			}
2433 rajveer 499
			if(feature.getFeatureDefinitionID() == 120089){
500
				PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
501
				tinySnippet = dataObject.getValue(); 
2171 rajveer 502
			}
2433 rajveer 503
			if(feature.getFeatureDefinitionID() == 120081){
504
				List<Bullet> bullets = feature.getBullets();
505
				int count = 1;
506
				for(Bullet bullet: bullets){
507
					PrimitiveDataObject dataObject = (PrimitiveDataObject)bullet.getDataObject();
508
					params.put("SNIPPET_"+count++, dataObject.getValue());
509
				}
2197 rajveer 510
			}
2171 rajveer 511
		}
512
 
2433 rajveer 513
 
514
		long categoryId = expEntity.getCategory().getID();
515
		params.put("PROD_NAME", prodName);
516
		params.put("URL", getEntityURL(expEntity));
517
		params.put("TITLE", title);
518
		params.put("BRAND_NAME", brandName);
519
		params.put("PRODUCT_NAME", productName);
520
		params.put("CATEGORY_ID", ((int)categoryId)+"");
521
		params.put("CATEGORY_NAME", categoryName);
522
		params.put("CATEGORY_URL", categoryName.replaceAll(" ", "-").toLowerCase() + "/" + categoryId);
523
		params.put("PRODUCT_URL", URLEncoder.encode("http://www.", "UTF-8") + "${domain}"  + URLEncoder.encode(this.getEntityURL(expEntity), "UTF-8"));
2547 rajveer 524
		if(expEntity.getCategory().getParentCategory().getID() != Utils.MOBILE_ACCESSORIES_CATEGORY){
2433 rajveer 525
			params.put("IS_MOBILE", "TRUE" );	
526
		}else{
527
			params.put("IS_MOBILE", "FALSE" );
528
		}
529
		params.put("CATALOG_ID", expEntity.getID()+"");
530
		params.put("TAGLINE", tagline);
531
		params.put("WARRANTY", warranty);
532
		params.put("TINY_SNIPPET", tinySnippet);
533
		params.put("IMAGE_PREFIX", getImagePrefix(expEntity));
534
		params.put("contentVersion", contentVersion);
2171 rajveer 535
 
2433 rajveer 536
		return params;
2171 rajveer 537
	}
2433 rajveer 538
 
2171 rajveer 539
 
2433 rajveer 540
	/**
541
	 * Generates content for the specified entity embedding links to the
542
	 * specified domain name.
543
	 * 
544
	 * The method updates the member variable problems in any of the following
545
	 * four cases:
546
	 * <ol>
547
	 * <li>The entity is not ready.
548
	 * <li>The category has not been updated yet. (Set to -1).
549
	 * <li>There are no items in the catalog corresponding to this entity.
550
	 * <li>There are no active or content-complete items in the catalog
551
	 * corresponding to this entity.
552
	 * <li>Neither the items have been updated nor the content has been updated.
553
	 * </ol>
554
	 * 
555
	 * @param entity
556
	 *            - Entity for which the content has to be generated.
557
	 * @param domain
558
	 *            - The domain name to be used to serve static content.
559
	 * @param exportPath
560
	 *            - Local file system path where content has to be generated.
561
	 * @return -True if content is generated successfully, False otherwise.
562
	 * @throws Exception
563
	 */
564
	public void generateContentForOneEntity(Entity entity, String exportPath) throws Exception{
565
		String mediaPath = Utils.EXPORT_MEDIA_PATH + entity.getID(); 
566
		deleteOldResources(mediaPath, exportPath + entity.getID()); //Remove old resources. ie images and html content
567
        ExpandedEntity expEntity = new ExpandedEntity(entity);
2171 rajveer 568
		long catalogId = expEntity.getID();
2433 rajveer 569
 
570
		//Create new directory
571
		File exportDir = new File(exportPath + catalogId);
572
		if(!exportDir.exists()) {
573
			exportDir.mkdir();
2171 rajveer 574
		}
2433 rajveer 575
 
576
		VelocityContext context = new VelocityContext();
577
 
578
		context.put("imagePrefix", getImagePrefix(expEntity));
579
		context.put("expentity", expEntity);
580
		context.put("contentVersion", this.contentVersion);
581
		context.put("defs", Catalog.getInstance().getDefinitionsContainer());
582
        context.put("helpdocs", CreationUtils.getHelpdocs());
583
        context.put("params", getEntityParameters(expEntity));
584
 
585
		List<String> filenames = new ArrayList<String>();
586
		filenames.add("ProductDetail");
587
		filenames.add("WidgetSnippet");
588
		filenames.add("HomeSnippet");
589
		filenames.add("SearchSnippet");
590
		filenames.add("CategorySnippet");
591
		filenames.add("SlideGuide");
2716 varun.gupt 592
		filenames.add("MyResearchSnippet");
2488 rajveer 593
 
2547 rajveer 594
		if(expEntity.getCategory().getParentCategory().getID() != Utils.MOBILE_ACCESSORIES_CATEGORY){
2488 rajveer 595
			filenames.add("PhonesIOwnSnippet");
2433 rajveer 596
			filenames.add("CompareProductSnippet");
597
			filenames.add("ComparisonSnippet");
598
			filenames.add("CompareProductSummarySnippet");
599
			// This method wont use any velocity file, So calling directly
600
			getSlidenamesSnippet(expEntity, exportPath);
2651 rajveer 601
			getRelatedAccessories(expEntity, exportPath);
2733 rajveer 602
			getMostComparedProducts(expEntity, exportPath);
2433 rajveer 603
		}
604
 
605
 
606
		// This method wont use any velocity file, So calling directly
607
		getProductPropertiesSnippet(expEntity, exportPath);
608
 
609
		applyVelocityTemplate(filenames,exportPath,context,catalogId);
610
 
611
		generateImages(expEntity.getID(), getImagePrefix(expEntity));
2171 rajveer 612
	}
613
 
2433 rajveer 614
	/**
615
	 * Get list of files and apply velocity templates on them
616
	 * @param filenames
617
	 * @param exportPath
618
	 * @param context
619
	 * @param catalogId
620
	 */
621
	private void applyVelocityTemplate(List<String> filenames, String exportPath, VelocityContext context, long catalogId){
2171 rajveer 622
		try {
2433 rajveer 623
			Properties p = new Properties();
624
			p.setProperty("resource.loader", "file");
625
			p.setProperty("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.FileResourceLoader");
626
			p.setProperty( "file.resource.loader.path", Utils.VTL_SRC_PATH);
627
			Velocity.init(p);
628
			for(String filename: filenames){
629
				Template template = Velocity.getTemplate(filename + ".vm");
630
				BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + catalogId + File.separator +filename+".vm")));
631
				template.merge(context, writer);
632
				writer.flush();
633
				writer.close();	
2197 rajveer 634
			}
2433 rajveer 635
		}catch (ResourceNotFoundException e) {
636
			// TODO Auto-generated catch block
637
			e.printStackTrace();
638
		} catch (IOException e) {
639
			// TODO Auto-generated catch block
640
			e.printStackTrace();
641
		} catch (ParseErrorException e) {
642
			// TODO Auto-generated catch block
643
			e.printStackTrace();
2171 rajveer 644
		} catch (Exception e) {
2433 rajveer 645
			// TODO Auto-generated catch block
2171 rajveer 646
			e.printStackTrace();
647
		}
2716 varun.gupt 648
	}	
649
}