Subversion Repositories SmartDukaan

Rev

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