Subversion Repositories SmartDukaan

Rev

Rev 2738 | Rev 3018 | 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>();
2735 rajveer 340
	    int individualLimit = 2;
2651 rajveer 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;
2740 rajveer 352
	    if(relatedAccessories!=null){
353
		    for(Long catID: priorityList){
354
		    	int individualCount = 0;
355
		    	List<Long> ents = relatedAccessories.get(catID);
356
		    	if(ents != null && !ents.isEmpty()){
357
		    		if(ents.size()>individualLimit){
358
		    			ents = ents.subList(0, individualLimit);
359
		    		}
360
		    		for(Long entID: ents){
361
		    			if(totalLimit > totalCount){
362
		    				sb.append(entID + "\n");
363
		    				individualCount++;
364
		    				totalCount++;
365
		    			}
366
		    		}
367
		    	}
368
		    }
2651 rajveer 369
	    }
370
 
371
        String exportFileName = exportPath + catalogId + File.separator + "RelatedAccessories.vm";
372
        File exportFile = new File(exportFileName);
373
        if(!exportFile.exists()) {
374
            exportFile.createNewFile();
375
        }
376
 
377
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportFile)));
378
 
379
        writer.write(sb.toString());
380
        writer.flush();
381
        writer.close();
382
 
383
	}
2733 rajveer 384
 
2651 rajveer 385
 
2433 rajveer 386
    /**
2733 rajveer 387
	 * Get most compared phones
388
	 * @param expEntity
389
	 * @param exportPath
390
	 * @throws Exception
391
	 */
392
    private void getMostComparedProducts(ExpandedEntity expEntity, String exportPath) throws Exception{
393
	    long catalogId = expEntity.getID();
394
 
395
	    Map<Long, Long> comparedPhones = CreationUtils.getComparisonStats().get(catalogId);
2738 rajveer 396
 
2733 rajveer 397
	    StringBuffer sb = new StringBuffer();
398
	    int maxCount = 10;
399
	    int count = 0;
2738 rajveer 400
	    if(comparedPhones != null){
401
		    for(Long entityID: comparedPhones.keySet()){
402
		    	if(count > maxCount){
403
					break;
404
				}
405
				sb.append(entityID + "\n");
406
				count++;
407
		    }
2733 rajveer 408
	    }
409
 
410
        String exportFileName = exportPath + catalogId + File.separator + "MostComparedProducts.vm";
411
        File exportFile = new File(exportFileName);
412
        if(!exportFile.exists()) {
413
            exportFile.createNewFile();
414
        }
415
 
416
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportFile)));
417
 
418
        writer.write(sb.toString());
419
        writer.flush();
420
        writer.close();
421
 
422
	}
423
 
424
    /**
2433 rajveer 425
     * Get the name of the product from entity. It considers null values also
426
     * @param expEntity
427
     * @return
428
     */
2726 rajveer 429
	public static String getProductName(ExpandedEntity expEntity){
2433 rajveer 430
		//FIXME Use stringbuilder
431
		String productName = ((expEntity.getBrand() != null) ? expEntity.getBrand().trim() + " " : "")
432
		+ ((expEntity.getModelName() != null) ? expEntity.getModelName().trim() + " " : "")
433
		+ (( expEntity.getModelNumber() != null ) ? expEntity.getModelNumber().trim() : "" );	
434
		return productName;
2171 rajveer 435
	}
436
 
2433 rajveer 437
	/**
438
	 * Get url of the entity. 
439
	 * @param expEntity
440
	 * @return
441
	 */
2171 rajveer 442
	private String getEntityURL(ExpandedEntity expEntity){
443
		String url = "/" + expEntity.getCategory().getParentCategory().getLabel().toLowerCase().replace(' ', '-') + "/";
2459 rajveer 444
		if(expEntity.getCategory().getParentCategory().getID() == Utils.ROOT_CATAGOEY){
445
			url = "/" + expEntity.getCategory().getLabel().toLowerCase().replace(' ', '-') + "/";
446
		}
447
 
2433 rajveer 448
		String productName = getProductName(expEntity);
449
		String productUrl = productName.toLowerCase().replace(' ', '-') + "-" + expEntity.getID();
2171 rajveer 450
		productUrl = productUrl.replaceAll("/", "-");
451
		url = url + productUrl;
2305 vikas 452
		url = url.replaceAll("-+", "-");
2171 rajveer 453
		return url;
454
	}
455
 
2433 rajveer 456
	/**
457
	 * get image prefix
458
	 * @param expEntity
459
	 * @return
460
	 */
2171 rajveer 461
	private String getImagePrefix(ExpandedEntity expEntity){
2433 rajveer 462
		String productName = getProductName(expEntity);
463
		String imagePrefix = productName.toLowerCase().replace(' ', '-');
2171 rajveer 464
		imagePrefix = imagePrefix.replaceAll("/", "-");
2367 rajveer 465
		imagePrefix = imagePrefix.replaceAll("-+", "-");
2171 rajveer 466
		return imagePrefix;
467
	}
468
 
2433 rajveer 469
 
470
	/**
471
	 * Get the required parameters for generating velocity content.
472
	 * @param expEntity
473
	 * @return
474
	 * @throws Exception
475
	 */
476
	private Map<String, String> getEntityParameters(ExpandedEntity expEntity) throws Exception{
477
		Map<String,String> params = new HashMap<String, String>();
478
		String title = getProductName(expEntity);
479
		String brandName = expEntity.getBrand().trim();
480
		String productName =  ((expEntity.getModelName() != null) ? expEntity.getModelName().trim() + " " : "")
481
		+ ((expEntity.getModelNumber() != null) ? expEntity.getModelNumber().trim() : "");
482
 
483
		String prodName = title;
484
		if (expEntity.getModelName() != null && !expEntity.getModelName().isEmpty() && (expEntity.getBrand().equals("Samsung") || expEntity.getBrand().equals("Sony Ericsson"))) {
485
			prodName = expEntity.getBrand().trim() + " " + ((expEntity.getModelName() != null) ? expEntity.getModelName().trim() : "");
486
		}
487
		String categoryName = expEntity.getCategory().getLabel();
488
		String tagline = "";
489
		String warranty = "";
490
		String tinySnippet = "";
491
		List<Feature>  features = expEntity.getSlide(130054).getFeatures();
492
		for(Feature feature: features){
493
			if(feature.getFeatureDefinitionID() == 120084){
494
				PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
495
				tagline = dataObject.getValue(); 
2197 rajveer 496
			}
2433 rajveer 497
			if(feature.getFeatureDefinitionID() == 120125){
498
				ExpandedFeature expFeature = new ExpandedFeature(feature);
499
				ExpandedBullet expBullet =expFeature.getExpandedBullets().get(0);
500
				if(expBullet != null){
501
					warranty = expBullet.getValue() + " "+ expBullet.getUnit().getShortForm();
2171 rajveer 502
				}
503
			}
2433 rajveer 504
			if(feature.getFeatureDefinitionID() == 120089){
505
				PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
506
				tinySnippet = dataObject.getValue(); 
2171 rajveer 507
			}
2433 rajveer 508
			if(feature.getFeatureDefinitionID() == 120081){
509
				List<Bullet> bullets = feature.getBullets();
510
				int count = 1;
511
				for(Bullet bullet: bullets){
512
					PrimitiveDataObject dataObject = (PrimitiveDataObject)bullet.getDataObject();
513
					params.put("SNIPPET_"+count++, dataObject.getValue());
514
				}
2197 rajveer 515
			}
2171 rajveer 516
		}
517
 
2433 rajveer 518
 
519
		long categoryId = expEntity.getCategory().getID();
520
		params.put("PROD_NAME", prodName);
521
		params.put("URL", getEntityURL(expEntity));
522
		params.put("TITLE", title);
523
		params.put("BRAND_NAME", brandName);
524
		params.put("PRODUCT_NAME", productName);
525
		params.put("CATEGORY_ID", ((int)categoryId)+"");
526
		params.put("CATEGORY_NAME", categoryName);
527
		params.put("CATEGORY_URL", categoryName.replaceAll(" ", "-").toLowerCase() + "/" + categoryId);
528
		params.put("PRODUCT_URL", URLEncoder.encode("http://www.", "UTF-8") + "${domain}"  + URLEncoder.encode(this.getEntityURL(expEntity), "UTF-8"));
2547 rajveer 529
		if(expEntity.getCategory().getParentCategory().getID() != Utils.MOBILE_ACCESSORIES_CATEGORY){
2433 rajveer 530
			params.put("IS_MOBILE", "TRUE" );	
531
		}else{
532
			params.put("IS_MOBILE", "FALSE" );
533
		}
534
		params.put("CATALOG_ID", expEntity.getID()+"");
535
		params.put("TAGLINE", tagline);
536
		params.put("WARRANTY", warranty);
537
		params.put("TINY_SNIPPET", tinySnippet);
538
		params.put("IMAGE_PREFIX", getImagePrefix(expEntity));
539
		params.put("contentVersion", contentVersion);
2171 rajveer 540
 
2433 rajveer 541
		return params;
2171 rajveer 542
	}
2433 rajveer 543
 
2171 rajveer 544
 
2433 rajveer 545
	/**
546
	 * Generates content for the specified entity embedding links to the
547
	 * specified domain name.
548
	 * 
549
	 * The method updates the member variable problems in any of the following
550
	 * four cases:
551
	 * <ol>
552
	 * <li>The entity is not ready.
553
	 * <li>The category has not been updated yet. (Set to -1).
554
	 * <li>There are no items in the catalog corresponding to this entity.
555
	 * <li>There are no active or content-complete items in the catalog
556
	 * corresponding to this entity.
557
	 * <li>Neither the items have been updated nor the content has been updated.
558
	 * </ol>
559
	 * 
560
	 * @param entity
561
	 *            - Entity for which the content has to be generated.
562
	 * @param domain
563
	 *            - The domain name to be used to serve static content.
564
	 * @param exportPath
565
	 *            - Local file system path where content has to be generated.
566
	 * @return -True if content is generated successfully, False otherwise.
567
	 * @throws Exception
568
	 */
569
	public void generateContentForOneEntity(Entity entity, String exportPath) throws Exception{
570
		String mediaPath = Utils.EXPORT_MEDIA_PATH + entity.getID(); 
571
		deleteOldResources(mediaPath, exportPath + entity.getID()); //Remove old resources. ie images and html content
572
        ExpandedEntity expEntity = new ExpandedEntity(entity);
2171 rajveer 573
		long catalogId = expEntity.getID();
2433 rajveer 574
 
575
		//Create new directory
576
		File exportDir = new File(exportPath + catalogId);
577
		if(!exportDir.exists()) {
578
			exportDir.mkdir();
2171 rajveer 579
		}
2433 rajveer 580
 
581
		VelocityContext context = new VelocityContext();
582
 
583
		context.put("imagePrefix", getImagePrefix(expEntity));
584
		context.put("expentity", expEntity);
585
		context.put("contentVersion", this.contentVersion);
586
		context.put("defs", Catalog.getInstance().getDefinitionsContainer());
587
        context.put("helpdocs", CreationUtils.getHelpdocs());
588
        context.put("params", getEntityParameters(expEntity));
589
 
590
		List<String> filenames = new ArrayList<String>();
591
		filenames.add("ProductDetail");
592
		filenames.add("WidgetSnippet");
593
		filenames.add("HomeSnippet");
594
		filenames.add("SearchSnippet");
595
		filenames.add("CategorySnippet");
596
		filenames.add("SlideGuide");
2716 varun.gupt 597
		filenames.add("MyResearchSnippet");
2488 rajveer 598
 
2547 rajveer 599
		if(expEntity.getCategory().getParentCategory().getID() != Utils.MOBILE_ACCESSORIES_CATEGORY){
2488 rajveer 600
			filenames.add("PhonesIOwnSnippet");
2433 rajveer 601
			filenames.add("CompareProductSnippet");
602
			filenames.add("ComparisonSnippet");
603
			filenames.add("CompareProductSummarySnippet");
604
			// This method wont use any velocity file, So calling directly
605
			getSlidenamesSnippet(expEntity, exportPath);
2651 rajveer 606
			getRelatedAccessories(expEntity, exportPath);
2733 rajveer 607
			getMostComparedProducts(expEntity, exportPath);
2433 rajveer 608
		}
609
 
610
 
611
		// This method wont use any velocity file, So calling directly
612
		getProductPropertiesSnippet(expEntity, exportPath);
613
 
614
		applyVelocityTemplate(filenames,exportPath,context,catalogId);
615
 
616
		generateImages(expEntity.getID(), getImagePrefix(expEntity));
2171 rajveer 617
	}
618
 
2433 rajveer 619
	/**
620
	 * Get list of files and apply velocity templates on them
621
	 * @param filenames
622
	 * @param exportPath
623
	 * @param context
624
	 * @param catalogId
625
	 */
626
	private void applyVelocityTemplate(List<String> filenames, String exportPath, VelocityContext context, long catalogId){
2171 rajveer 627
		try {
2433 rajveer 628
			Properties p = new Properties();
629
			p.setProperty("resource.loader", "file");
630
			p.setProperty("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.FileResourceLoader");
631
			p.setProperty( "file.resource.loader.path", Utils.VTL_SRC_PATH);
632
			Velocity.init(p);
633
			for(String filename: filenames){
634
				Template template = Velocity.getTemplate(filename + ".vm");
635
				BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + catalogId + File.separator +filename+".vm")));
636
				template.merge(context, writer);
637
				writer.flush();
638
				writer.close();	
2197 rajveer 639
			}
2433 rajveer 640
		}catch (ResourceNotFoundException e) {
641
			// TODO Auto-generated catch block
642
			e.printStackTrace();
643
		} catch (IOException e) {
644
			// TODO Auto-generated catch block
645
			e.printStackTrace();
646
		} catch (ParseErrorException e) {
647
			// TODO Auto-generated catch block
648
			e.printStackTrace();
2171 rajveer 649
		} catch (Exception e) {
2433 rajveer 650
			// TODO Auto-generated catch block
2171 rajveer 651
			e.printStackTrace();
652
		}
2716 varun.gupt 653
	}	
654
}