Subversion Repositories SmartDukaan

Rev

Rev 3888 | Rev 3929 | 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 {
3888 mandeep.dh 50
    private static final String SPACE = " ";
51
    private static final String HYPHON = "-";
52
 
2171 rajveer 53
	String contentVersion;  
54
 
55
	public NewVUI(Long contentVersion) throws Exception {
2367 rajveer 56
		this.contentVersion = contentVersion.toString();
2171 rajveer 57
	}
58
 
59
	/**
2433 rajveer 60
	 * Utility method to delete a directory.
61
	 * @param dir
62
	 * @return
2171 rajveer 63
	 */
2433 rajveer 64
	private boolean deleteDir(File dir) {
2171 rajveer 65
	    if (dir.isDirectory()) {
66
	        String[] children = dir.list();
67
	        for (int i=0; i<children.length; i++) {
68
	            boolean success = deleteDir(new File(dir, children[i]));
69
	            if (!success) {
70
	                return false;
71
	            }
72
	        }
73
	    }
74
	    // The directory is now empty so delete it
75
	    return dir.delete();
76
	}
77
 
2433 rajveer 78
	/**
79
	 * Delete old resources of the entity for which content needs to be regenerated  
80
	 * @param mediaPath
81
	 * @param contentPath
82
	 */
2171 rajveer 83
	private void deleteOldResources(String mediaPath, String contentPath) {
84
		File f = new File(contentPath);
85
		if(f.exists()){
86
			deleteDir(f);
87
		}
88
 
89
		f = new File(mediaPath);
90
		if(f.exists()){
91
			deleteDir(f);
92
		}
93
	}
94
 
3018 rajveer 95
 
96
	private void copyDocuments(ExpandedEntity expEntity) throws IOException {
97
		long catalogId = expEntity.getID();
98
		String sourceDirectory = Utils.CONTENT_DB_PATH + "media" + File.separator + catalogId;
99
		String destinationDirectory = Utils.EXPORT_PATH + "documents" + File.separator + catalogId;
100
 
101
		/*
102
		 * Create the directory for this entity if it didn't exist.
103
		 */
104
		File destFile = new File(destinationDirectory);
105
		if (!destFile.exists()) {
106
			destFile.mkdir();
107
		}
108
 
109
		ExpandedSlide expSlide = expEntity.getExpandedSlide(Utils.AFTER_SALES_SLIDE_DEFINITION_ID);
3021 rajveer 110
		if(expSlide == null || expSlide.getFreeformContent()==null){
3020 rajveer 111
			return;
112
		}
3018 rajveer 113
		Map<String, Media> medias = expSlide.getFreeformContent().getMedias();
114
		List<String> documentLabels = expSlide.getFreeformContent().getDocumentLabels();
3020 rajveer 115
		if((documentLabels == null || documentLabels.isEmpty())){
116
			return;
117
		}else{
3018 rajveer 118
			for(String documentLabel: documentLabels){
119
				Media document = medias.get(documentLabel);
120
				String fileName = document.getFileName();
121
				copyFile(sourceDirectory + File.separator + fileName, destinationDirectory + File.separator + fileName);
122
			}
123
		}
124
	}
125
 
126
 
2433 rajveer 127
	/**
128
	 * It Actually copies the images from some given directory to export directory.
129
	 * It also attaches the imagePrefix at the end of image name. 
130
	 * @param catalogId
131
	 * @param imagePrefix
132
	 * @throws IOException
133
	 */
2171 rajveer 134
	private void generateImages(long catalogId, String imagePrefix) throws IOException {
135
		String globalImageDirPath = Utils.CONTENT_DB_PATH + "media" + File.separator;
136
		String globalDefaultImagePath = globalImageDirPath + "default.jpg";
137
 
138
		String imageDirPath = globalImageDirPath + catalogId + File.separator;
139
		String defaultImagePath = imageDirPath + "default.jpg";
140
 
141
		/*
142
		 * Create the directory for this entity if it didn't exist.
143
		 */
144
		File f = new File(globalImageDirPath + catalogId);
145
		if (!f.exists()) {
146
			f.mkdir();
147
		}
148
 
149
		/*
150
		 * If the default image is not present for this entity, copy the global
151
		 * default image.
152
		 * TODO: This part will be moved to the Jython Script
153
		 */
154
		File f3 = new File(defaultImagePath);
155
		if (!f3.exists()) {
156
		        copyFile(globalDefaultImagePath, defaultImagePath);
157
		    }
158
 
159
		String exportPath = Utils.EXPORT_MEDIA_PATH + catalogId;
160
		/*
161
		 * Copying the generated content from db/media to export/media. This
162
		 * will also insert a timestamp tag in the file names.
163
		 */
164
		File sourceFile = new File(globalImageDirPath + catalogId);
165
		File destinationFile = new File(exportPath);
2198 rajveer 166
		copyDirectory(sourceFile, destinationFile, imagePrefix);
2171 rajveer 167
 
168
		/*
169
		 * Copy the thumbnail and the icon files. This is required so that we can display the
170
		 * thumbnail on the cart page and icon on the facebook.
171
		 */
2198 rajveer 172
		copyFile(imageDirPath + "thumbnail.jpg", exportPath + File.separator + "thumbnail.jpg");
173
		copyFile(imageDirPath + "icon.jpg", exportPath + File.separator + "icon.jpg");
2171 rajveer 174
		}
175
 
176
	/**
177
	 * Copies the contents of the input file into the output file. Creates the
178
	 * output file if it doesn't exist already.
179
	 * 
180
	 * @param inputFile
181
	 *            File to be copied.
182
	 * @param outputFile
183
	 *            File to be created.
184
	 * @throws IOException
185
	 */
186
	private void copyFile(String inputFile, String outputFile) throws IOException {
187
		File sourceFile = new File(inputFile);
188
		File destinationFile = new File(outputFile);
2206 rajveer 189
 
2171 rajveer 190
		if (!destinationFile.exists())
191
			destinationFile.createNewFile();
192
 
193
		InputStream in = new FileInputStream(sourceFile);
2305 vikas 194
	    OutputStream out = new FileOutputStream(destinationFile);
2171 rajveer 195
		// Copy the bits from instream to outstream
196
		byte[] buf = new byte[1024];
197
		int len;
198
		while ((len = in.read(buf)) > 0) {
199
			out.write(buf, 0, len);
200
		}
201
		in.close();
202
		out.close();
203
	}
204
 
2433 rajveer 205
 
206
	/**
207
	 * Copy the images from one directory to other. It also renames files while copying.
208
	 * If targetLocation does not exist, it will be created.
209
	 * @param sourceLocation
210
	 * @param targetLocation
211
	 * @param imagePrefix
212
	 * @throws IOException
213
	 */
2171 rajveer 214
	public void copyDirectory(File sourceLocation , File targetLocation, String imagePrefix) throws IOException {
215
 
216
	    if (sourceLocation.isDirectory()) {
217
	        if (!targetLocation.exists()) {
218
	            targetLocation.mkdir();
219
	        }
220
 
221
	        String[] children = sourceLocation.list();
222
	        for (int i=0; i<children.length; i++) {
223
	            copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), imagePrefix);
224
	        }
225
	    } else {
226
	        InputStream in = new FileInputStream(sourceLocation);
227
 
228
        	String fileName = targetLocation.getName().split("\\.")[0];
229
        	String fileExt = targetLocation.getName().split("\\.")[1];
230
        	String newFileName = targetLocation.getParent() + File.separator + imagePrefix + "-" + fileName + "-" + this.contentVersion + "." + fileExt; 
231
 
232
 
233
	        //String fileName = targetLocation
234
	        OutputStream out = new FileOutputStream(newFileName);
235
 
236
	        // Copy the bits from instream to outstream
237
	        byte[] buf = new byte[1024];
238
	        int len;
239
	        while ((len = in.read(buf)) > 0) {
240
	            out.write(buf, 0, len);
241
	        }
242
	        in.close();
243
	        out.close();
244
	    }
245
	}
246
 
2433 rajveer 247
	/**
248
	 * Get the commonly used product properties and store them in a file.  
249
	 * @param expEntity
250
	 * @param exportPath
251
	 */
2305 vikas 252
	private  void getProductPropertiesSnippet(ExpandedEntity expEntity, String exportPath) {
253
        long catalogId = expEntity.getID();
254
        try {
255
            expEntity = CreationUtils.getExpandedEntity(catalogId);
256
        } catch (Exception e) {
257
            e.printStackTrace();
258
        }
259
 
260
        String metaDescription = "";
261
        String metaKeywords = "";
3018 rajveer 262
        String entityUrl = EntityUtils.getEntityURL(expEntity);
2305 vikas 263
        String title = "";
264
 
265
        List<Feature>  features = expEntity.getSlide(130054).getFeatures();
266
        for(Feature feature: features){
267
            if(feature.getFeatureDefinitionID() == 120132){
268
                PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
269
                title = dataObject.getValue(); 
270
            }
271
            if(feature.getFeatureDefinitionID() == 120133){
272
                PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
273
                metaDescription = dataObject.getValue();
274
            }
275
            if(feature.getFeatureDefinitionID() == 120134){
276
                PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
277
                metaKeywords = dataObject.getValue();
278
            }
279
        }
2171 rajveer 280
 
2305 vikas 281
        try {
282
            JSONObject props = new JSONObject();
3829 rajveer 283
            Category category = expEntity.getCategory();
284
            String categoryName = category.getLabel();
285
 
2305 vikas 286
            props.put("metaDescription", metaDescription);
287
            props.put("metaKeywords", metaKeywords);
288
            props.put("entityUrl", entityUrl);
289
            props.put("title", title);
3018 rajveer 290
            props.put("name", EntityUtils.getProductName(expEntity));
3829 rajveer 291
            boolean displayAccessories;
3719 mandeep.dh 292
            if(expEntity.getCategory().getParentCategory().getID() != Utils.MOBILE_ACCESSORIES_CATEGORY && expEntity.getCategory().getID() != Utils.LAPTOPS_CATEGORY){
3829 rajveer 293
            	props.put("displayAccessories", "TRUE");
294
            	displayAccessories = true;
2651 rajveer 295
    		}else{
296
    			props.put("displayAccessories", "FALSE" );
3829 rajveer 297
    			displayAccessories = false;
2651 rajveer 298
    		}   
2433 rajveer 299
 
3829 rajveer 300
            props.put("categoryName", categoryName);
301
            props.put("categoryUrl", categoryName.replaceAll(" ", "-").toLowerCase() + "/" + category.getID());
302
            String categoryUrl = categoryName.replaceAll(" ", "-").toLowerCase() + "/" + category.getID();
2651 rajveer 303
 
3829 rajveer 304
            String brandUrl = expEntity.getBrand().toLowerCase().replace(' ', '-');
305
 
306
            String breadCrumb = "<a href='/'>Home</a>&nbsp;&gt;&nbsp;" + 
307
								"<a href='/" +  categoryUrl + "'>" + categoryName + "</a>&nbsp;&gt;&nbsp;";
308
            if(displayAccessories){
309
            	breadCrumb = breadCrumb +  "<a href='/" + brandUrl + "'>" + expEntity.getBrand() + "</a>";
310
            }else{
311
            	breadCrumb =  breadCrumb + "<a>" + expEntity.getBrand() + "</a>";	
312
            }
313
            breadCrumb = breadCrumb +  "&nbsp;<a>" + expEntity.getModelName().trim() + " " + expEntity.getModelNumber().trim() + "</a>";
314
            props.put("breadCrumb", breadCrumb);
315
 
316
 
2305 vikas 317
            String exportFileName = exportPath + catalogId + File.separator
2367 rajveer 318
                    + "ProductPropertiesSnippet.vm";
2305 vikas 319
            File exportFile = new File(exportFileName);
320
            if (!exportFile.exists()) {
321
                exportFile.createNewFile();
322
            }
2171 rajveer 323
 
2305 vikas 324
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
325
                    new FileOutputStream(exportFile)));
326
 
327
            writer.write(props.toString());
328
 
329
            writer.flush();
330
            writer.close();
331
        } catch (Exception e) {
332
            e.printStackTrace();
333
        }
2171 rajveer 334
	}
2305 vikas 335
 
2433 rajveer 336
	/**
337
	 * Get slide names and write them in a file. This file will be used in comparison.
338
	 * @param expEntity
339
	 * @param exportPath
340
	 * @throws Exception
341
	 */
342
    private void getSlidenamesSnippet(ExpandedEntity expEntity, String exportPath) throws Exception{
2171 rajveer 343
	    long catalogId = expEntity.getID();
344
 
345
	    StringBuilder slideNames = new StringBuilder();
2433 rajveer 346
	    //TODO Investigate why brand + model number is used ?
2171 rajveer 347
	    slideNames.append(expEntity.getBrand() + " " + expEntity.getModelNumber() + " " + expEntity.getModelName() + "\n");
348
 
349
	    Map<Long, Double> slideScores = CreationUtils.getSlideComparisonScores(catalogId);
350
 
351
	    for(ExpandedSlide expSlide: expEntity.getExpandedSlides()){
3231 rajveer 352
	        if(expSlide.getSlideDefinitionID() == Utils.SUMMARY_SLIDE_DEFINITION_ID || expSlide.getSlideDefinitionID() == Utils.AFTER_SALES_SLIDE_DEFINITION_ID ){
2171 rajveer 353
	            continue;
354
	        }
355
	        slideNames.append(expSlide.getSlideDefinition().getLabel() + "!!!");
356
 
357
	        String bucketName = "None";
358
	        if(Catalog.getInstance().getDefinitionsContainer().getComparisonBucketName(expEntity.getCategoryID(), expSlide.getSlideDefinitionID()) != null){
359
	            bucketName = Catalog.getInstance().getDefinitionsContainer().getComparisonBucketName(expEntity.getCategoryID(), expSlide.getSlideDefinitionID());
360
	        }
361
	        slideNames.append(bucketName + "!!!");
362
 
363
	        double score = 0;
364
	        if(slideScores.get(expSlide.getSlideDefinitionID())!=null){
365
	            score = slideScores.get(expSlide.getSlideDefinitionID());
366
	        }
367
 
368
	        DecimalFormat oneDForm = new DecimalFormat("#.#");
369
	        score = Double.valueOf(oneDForm.format(score));
370
 
371
	        slideNames.append(score + "\n");
372
	    }
373
 
2367 rajveer 374
        String exportFileName = exportPath + catalogId + File.separator + "SlideNamesSnippet.vm";
2171 rajveer 375
        File exportFile = new File(exportFileName);
376
        if(!exportFile.exists()) {
377
            exportFile.createNewFile();
378
        }
379
 
380
        BufferedWriter writer = new BufferedWriter(
381
            new OutputStreamWriter(new FileOutputStream(exportFile)));
382
 
383
        writer.write(slideNames.toString());
384
        writer.flush();
385
        writer.close();
386
 
387
	}
2651 rajveer 388
 
2433 rajveer 389
 
2651 rajveer 390
	/**
391
	 * Get related accessories
392
	 * @param expEntity
393
	 * @param exportPath
394
	 * @throws Exception
395
	 */
396
    private void getRelatedAccessories(ExpandedEntity expEntity, String exportPath) throws Exception{
397
	    long catalogId = expEntity.getID();
398
 
399
	    Map<Long, List<Long>> relatedAccessories = CreationUtils.getRelatedAccessories().get(catalogId);
400
	    List<Long> priorityList = new ArrayList<Long>();
2735 rajveer 401
	    int individualLimit = 2;
2651 rajveer 402
	    int totalLimit = 10;
403
	    priorityList.add(Utils.CARRYING_CASE);
404
	    priorityList.add(Utils.SCREEN_GUARD);
405
	    priorityList.add(Utils.BATTERY);
406
	    priorityList.add(Utils.MEMORY_CARD);
407
	    priorityList.add(Utils.BLUETOOTH_HEADSET);
408
	    priorityList.add(Utils.HEADSET);
409
	    priorityList.add(Utils.CHARGER);
410
 
411
	    StringBuffer sb = new StringBuffer();
412
	    int totalCount = 0;
2740 rajveer 413
	    if(relatedAccessories!=null){
414
		    for(Long catID: priorityList){
415
		    	int individualCount = 0;
416
		    	List<Long> ents = relatedAccessories.get(catID);
417
		    	if(ents != null && !ents.isEmpty()){
418
		    		if(ents.size()>individualLimit){
419
		    			ents = ents.subList(0, individualLimit);
420
		    		}
421
		    		for(Long entID: ents){
422
		    			if(totalLimit > totalCount){
423
		    				sb.append(entID + "\n");
424
		    				individualCount++;
425
		    				totalCount++;
426
		    			}
427
		    		}
428
		    	}
429
		    }
2651 rajveer 430
	    }
431
 
432
        String exportFileName = exportPath + catalogId + File.separator + "RelatedAccessories.vm";
433
        File exportFile = new File(exportFileName);
434
        if(!exportFile.exists()) {
435
            exportFile.createNewFile();
436
        }
437
 
438
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportFile)));
439
 
440
        writer.write(sb.toString());
441
        writer.flush();
442
        writer.close();
443
 
444
	}
2733 rajveer 445
 
2651 rajveer 446
 
2433 rajveer 447
    /**
2733 rajveer 448
	 * Get most compared phones
449
	 * @param expEntity
450
	 * @param exportPath
451
	 * @throws Exception
452
	 */
453
    private void getMostComparedProducts(ExpandedEntity expEntity, String exportPath) throws Exception{
454
	    long catalogId = expEntity.getID();
455
 
456
	    Map<Long, Long> comparedPhones = CreationUtils.getComparisonStats().get(catalogId);
2738 rajveer 457
 
2733 rajveer 458
	    StringBuffer sb = new StringBuffer();
459
	    int maxCount = 10;
460
	    int count = 0;
2738 rajveer 461
	    if(comparedPhones != null){
462
		    for(Long entityID: comparedPhones.keySet()){
463
		    	if(count > maxCount){
464
					break;
465
				}
466
				sb.append(entityID + "\n");
467
				count++;
468
		    }
2733 rajveer 469
	    }
470
 
471
        String exportFileName = exportPath + catalogId + File.separator + "MostComparedProducts.vm";
472
        File exportFile = new File(exportFileName);
473
        if(!exportFile.exists()) {
474
            exportFile.createNewFile();
475
        }
476
 
477
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportFile)));
478
 
479
        writer.write(sb.toString());
480
        writer.flush();
481
        writer.close();
482
 
483
	}
484
 
2171 rajveer 485
 
2433 rajveer 486
 
487
	/**
488
	 * Get the required parameters for generating velocity content.
489
	 * @param expEntity
490
	 * @return
491
	 * @throws Exception
492
	 */
493
	private Map<String, String> getEntityParameters(ExpandedEntity expEntity) throws Exception{
3888 mandeep.dh 494
        Map<String, String> params = new HashMap<String, String>();
495
        String title = EntityUtils.getProductName(expEntity);
496
        String brandName = expEntity.getBrand().trim();
497
        String productName = ((expEntity.getModelName() != null) ? expEntity
498
                .getModelName().trim() + SPACE : "")
499
                + ((expEntity.getModelNumber() != null) ? expEntity
500
                        .getModelNumber().trim() : "");
2171 rajveer 501
 
3888 mandeep.dh 502
        String prodName = title;
503
        if (expEntity.getModelName() != null
504
                && !expEntity.getModelName().isEmpty()
505
                && (expEntity.getBrand().equals("Samsung") || expEntity
506
                        .getBrand().equals("Sony Ericsson"))) {
507
            prodName = expEntity.getBrand().trim()
508
                    + SPACE
509
                    + ((expEntity.getModelName() != null) ? expEntity
510
                            .getModelName().trim() : "");
511
        }
512
        String categoryName = expEntity.getCategory().getLabel();
513
        String tagline = "";
514
        String warranty = "";
515
        String tinySnippet = "";
516
        List<Feature> features = expEntity.getSlide(130054).getFeatures();
517
        for (Feature feature : features) {
518
            if (feature.getFeatureDefinitionID() == 120084) {
519
                PrimitiveDataObject dataObject = (PrimitiveDataObject) feature
520
                        .getBullets().get(0).getDataObject();
521
                tagline = dataObject.getValue();
522
            }
523
            if (feature.getFeatureDefinitionID() == 120089) {
524
                PrimitiveDataObject dataObject = (PrimitiveDataObject) feature
525
                        .getBullets().get(0).getDataObject();
526
                tinySnippet = dataObject.getValue();
527
            }
528
            if (feature.getFeatureDefinitionID() == 120081) {
529
                List<Bullet> bullets = feature.getBullets();
530
                int count = 1;
531
                for (Bullet bullet : bullets) {
532
                    PrimitiveDataObject dataObject = (PrimitiveDataObject) bullet
533
                            .getDataObject();
534
                    params.put("SNIPPET_" + count++, dataObject.getValue());
535
                }
536
            }
537
        }
3869 rajveer 538
 
3888 mandeep.dh 539
        // Creating warranty string!
540
        for (Slide slide : expEntity.getSlide(130054).getChildrenSlides()) {
541
            if (slide.getSlideDefinitionID() == 130105) {
542
                ExpandedSlide expSlide = new ExpandedSlide(slide);
543
                Feature warrantyDurationFeature = expSlide.getExpandedFeature(120125);
544
                if (warrantyDurationFeature != null) {
545
                    ExpandedFeature expFeature = new ExpandedFeature(warrantyDurationFeature);
546
                    ExpandedBullet expBullet = expFeature.getExpandedBullets().get(0);
547
                    if (expBullet != null) {
548
                        String shortForm = expBullet.getUnit().getShortForm();
3869 rajveer 549
 
3888 mandeep.dh 550
                        // Append 's' to month and year
551
                        if (!expBullet.getValue().trim().equals("1")) {
552
                            shortForm += "s";
553
                        }
554
                        warranty += expBullet.getValue() + SPACE + shortForm;
555
                    }
556
                }
3869 rajveer 557
 
3888 mandeep.dh 558
                Feature warrantyTypeFeature = expSlide.getExpandedFeature(120219);
559
                if (warrantyTypeFeature != null) {
560
                    ExpandedFeature expFeature = new ExpandedFeature(warrantyTypeFeature);
561
                    ExpandedBullet expBullet = expFeature.getExpandedBullets().get(0);
562
                    if (expBullet != null) {
563
                        warranty += SPACE + expBullet.getExpandedEnumDataObject()
564
                                        .getEnumValue().getValue();
565
                    }
566
                }
3869 rajveer 567
 
3888 mandeep.dh 568
                Feature warrantyCoverageFeature = expSlide.getExpandedFeature(120220);
569
                if (warrantyCoverageFeature != null) {
570
                    ExpandedFeature expFeature = new ExpandedFeature(warrantyCoverageFeature);
571
                    ExpandedBullet expBullet = expFeature.getExpandedBullets().get(0);
572
                    if (expBullet != null) {
573
                        warranty += SPACE + HYPHON + SPACE + expBullet.getExpandedEnumDataObject().getEnumValue().getValue();
574
                    }
575
                }
576
            }
577
        }
3869 rajveer 578
 
3888 mandeep.dh 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(SPACE, HYPHON)
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);
3889 mandeep.dh 605
        params.put("IMAGE_PREFIX", EntityUtils.getImagePrefix(expEntity));
3888 mandeep.dh 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
}