Subversion Repositories SmartDukaan

Rev

Rev 2433 | Rev 2488 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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