Subversion Repositories SmartDukaan

Rev

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