Subversion Repositories SmartDukaan

Rev

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