Subversion Repositories SmartDukaan

Rev

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