Subversion Repositories SmartDukaan

Rev

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