Subversion Repositories SmartDukaan

Rev

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