Subversion Repositories SmartDukaan

Rev

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