Subversion Repositories SmartDukaan

Rev

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