Subversion Repositories SmartDukaan

Rev

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