Subversion Repositories SmartDukaan

Rev

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