Subversion Repositories SmartDukaan

Rev

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