Subversion Repositories SmartDukaan

Rev

Rev 3929 | Rev 3991 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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