Subversion Repositories SmartDukaan

Rev

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