Subversion Repositories SmartDukaan

Rev

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