Subversion Repositories SmartDukaan

Rev

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