Subversion Repositories SmartDukaan

Rev

Rev 5261 | Rev 5322 | 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 = "";
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
            }
3929 mandeep.dh 376
            if (feature.getFeatureDefinitionID() == 120134) {
377
                PrimitiveDataObject dataObject = (PrimitiveDataObject) feature
378
                        .getBullets().get(0).getDataObject();
2305 vikas 379
                metaKeywords = dataObject.getValue();
380
            }
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);
389
            props.put("metaKeywords", metaKeywords);
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();
396
            if(parentCategory.isHasAccessories()){
3929 mandeep.dh 397
                props.put("displayAccessories", "TRUE");
398
                displayAccessories = true;
399
            }else{
400
                props.put("displayAccessories", "FALSE" );
401
                displayAccessories = false;
402
            }  
403
 
3829 rajveer 404
            props.put("categoryName", categoryName);
3929 mandeep.dh 405
            props.put("categoryUrl", categoryName.replaceAll(SPACE, "-").toLowerCase() + "/" + category.getID());
406
            String categoryUrl = categoryName.replaceAll(SPACE, "-").toLowerCase() + "/" + category.getID();
407
 
3829 rajveer 408
            String brandUrl = expEntity.getBrand().toLowerCase().replace(' ', '-');
3929 mandeep.dh 409
 
410
            String breadCrumb = "<a href='/'>Home</a>&nbsp;&gt;&nbsp;" +
411
                                "<a href='/" +  categoryUrl + "'>" + categoryName + "</a>&nbsp;&gt;&nbsp;";
3829 rajveer 412
            if(displayAccessories){
3929 mandeep.dh 413
                breadCrumb = breadCrumb +  "<a href='/" + brandUrl + "'>" + expEntity.getBrand() + "</a>";
3829 rajveer 414
            }else{
3929 mandeep.dh 415
                breadCrumb =  breadCrumb + "<a>" + expEntity.getBrand() + "</a>";  
3829 rajveer 416
            }
3929 mandeep.dh 417
            breadCrumb = breadCrumb +  "&nbsp;<a>" + expEntity.getModelName().trim() + SPACE + expEntity.getModelNumber().trim() + "</a>";
3829 rajveer 418
            props.put("breadCrumb", breadCrumb);
3929 mandeep.dh 419
 
420
 
2305 vikas 421
            String exportFileName = exportPath + catalogId + File.separator
2367 rajveer 422
                    + "ProductPropertiesSnippet.vm";
2305 vikas 423
            File exportFile = new File(exportFileName);
424
            if (!exportFile.exists()) {
425
                exportFile.createNewFile();
426
            }
2171 rajveer 427
 
2305 vikas 428
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
429
                    new FileOutputStream(exportFile)));
430
 
431
            writer.write(props.toString());
432
 
433
            writer.flush();
434
            writer.close();
435
        } catch (Exception e) {
3929 mandeep.dh 436
            log.error("Error generating JSON", e);
2305 vikas 437
        }
3929 mandeep.dh 438
    }
2305 vikas 439
 
3929 mandeep.dh 440
    /**
441
     * Get slide names and write them in a file. This file will be used in
442
     * comparison.
443
     *
444
     * @param expEntity
445
     * @param exportPath
446
     * @throws Exception
447
     */
448
    private void getSlidenamesSnippet(ExpandedEntity expEntity,
449
            String exportPath) throws Exception {
450
        long catalogId = expEntity.getID();
2171 rajveer 451
 
3929 mandeep.dh 452
        StringBuilder slideNames = new StringBuilder();
453
 
454
        // TODO Investigate why brand + model number is used ?
455
        slideNames.append(expEntity.getBrand() + SPACE
456
                + expEntity.getModelNumber() + SPACE + expEntity.getModelName()
457
                + "\n");
5048 amit.gupta 458
        slideNames.append(expEntity.getBrand() + SPACE +
5050 amit.gupta 459
        		(StringUtils.isNotEmpty(expEntity.getModelName()) ?  expEntity.getModelName() : expEntity.getModelNumber())
5048 amit.gupta 460
        		+ "\n");
3929 mandeep.dh 461
 
462
        Map<Long, Double> slideScores = CreationUtils
463
                .getSlideComparisonScores(catalogId);
464
 
465
        for (ExpandedSlide expSlide : expEntity.getExpandedSlides()) {
466
            if (expSlide.getSlideDefinitionID() == Utils.SUMMARY_SLIDE_DEFINITION_ID
467
                    || expSlide.getSlideDefinitionID() == Utils.AFTER_SALES_SLIDE_DEFINITION_ID) {
468
                continue;
469
            }
470
            slideNames.append(expSlide.getSlideDefinition().getLabel() + "!!!");
471
 
472
            String bucketName = "None";
473
            if (Catalog
474
                    .getInstance()
475
                    .getDefinitionsContainer()
476
                    .getComparisonBucketName(expEntity.getCategoryID(),
477
                            expSlide.getSlideDefinitionID()) != null) {
478
                bucketName = Catalog
479
                        .getInstance()
480
                        .getDefinitionsContainer()
481
                        .getComparisonBucketName(expEntity.getCategoryID(),
482
                                expSlide.getSlideDefinitionID());
483
            }
484
            slideNames.append(bucketName + "!!!");
485
 
486
            double score = 0;
487
            if (slideScores.get(expSlide.getSlideDefinitionID()) != null) {
488
                score = slideScores.get(expSlide.getSlideDefinitionID());
489
            }
490
 
491
            DecimalFormat oneDForm = new DecimalFormat("#.#");
492
            score = Double.valueOf(oneDForm.format(score));
493
 
494
            slideNames.append(score + "\n");
495
        }
496
 
497
        String exportFileName = exportPath + catalogId + File.separator
498
                + "SlideNamesSnippet.vm";
2171 rajveer 499
        File exportFile = new File(exportFileName);
3929 mandeep.dh 500
        if (!exportFile.exists()) {
2171 rajveer 501
            exportFile.createNewFile();
502
        }
503
 
3929 mandeep.dh 504
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
505
                new FileOutputStream(exportFile)));
506
 
2171 rajveer 507
        writer.write(slideNames.toString());
508
        writer.flush();
509
        writer.close();
2651 rajveer 510
 
3929 mandeep.dh 511
    }
512
 
513
    /**
514
     * Get related accessories
515
     *
516
     * @param expEntity
517
     * @param exportPath
518
     * @throws Exception
519
     */
520
    private void getRelatedAccessories(ExpandedEntity expEntity,
521
            String exportPath) throws Exception {
522
        long catalogId = expEntity.getID();
523
 
524
        Map<Long, List<Long>> relatedAccessories = CreationUtils
525
                .getRelatedAccessories().get(catalogId);
526
        List<Long> priorityList = new ArrayList<Long>();
527
        int individualLimit = 2;
528
        int totalLimit = 10;
529
        priorityList.add(Utils.CARRYING_CASE);
530
        priorityList.add(Utils.SCREEN_GUARD);
531
        priorityList.add(Utils.BATTERY);
532
        priorityList.add(Utils.MEMORY_CARD);
533
        priorityList.add(Utils.BLUETOOTH_HEADSET);
534
        priorityList.add(Utils.HEADSET);
535
        priorityList.add(Utils.CHARGER);
536
 
537
        StringBuffer sb = new StringBuffer();
538
        int totalCount = 0;
539
        if (relatedAccessories != null) {
540
            for (Long catID : priorityList) {
541
                int individualCount = 0;
542
                List<Long> ents = relatedAccessories.get(catID);
543
                if (ents != null && !ents.isEmpty()) {
4802 amit.gupta 544
                	Predicate activeOnly =new Predicate() {
545
 
546
						@Override
547
						public boolean evaluate(Object arg0) {
548
							Long entityId = (Long)arg0;
549
							boolean returnVal = false;
5173 amit.gupta 550
							List<Item> items = null;
4802 amit.gupta 551
							try {
5173 amit.gupta 552
								try {
553
									items = cl.getItemsByCatalogId(entityId);
554
								} catch (Exception e) {
555
									Logger.log("Error:", e);
556
									cl = new CatalogClient().getClient();
557
									items = cl.getItemsByCatalogId(entityId);
558
								}
4802 amit.gupta 559
								for(Item item: items){
560
									if(item.getItemStatus().equals(status.ACTIVE)){
561
										returnVal = true;
562
										break;
563
									}
564
								}
565
							} catch (Exception e) {
566
								// TODO Auto-generated catch block
567
								log.error("Error accessing thrift service", e);
568
							}
569
							return returnVal;
570
						}
571
					};
572
					CollectionUtils.filter(ents, activeOnly);
3929 mandeep.dh 573
                    if (ents.size() > individualLimit) {
574
                        ents = ents.subList(0, individualLimit);
575
                    }
576
                    for (Long entID : ents) {
577
                        if (totalLimit > totalCount) {
578
                            sb.append(entID + "\n");
579
                            individualCount++;
580
                            totalCount++;
581
                        }
582
                    }
583
                }
584
            }
585
        }
586
 
587
        String exportFileName = exportPath + catalogId + File.separator
588
                + "RelatedAccessories.vm";
2651 rajveer 589
        File exportFile = new File(exportFileName);
3929 mandeep.dh 590
        if (!exportFile.exists()) {
2651 rajveer 591
            exportFile.createNewFile();
592
        }
593
 
3929 mandeep.dh 594
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
595
                new FileOutputStream(exportFile)));
596
 
2651 rajveer 597
        writer.write(sb.toString());
598
        writer.flush();
599
        writer.close();
2733 rajveer 600
 
3929 mandeep.dh 601
    }
602
 
2433 rajveer 603
    /**
3929 mandeep.dh 604
     * Get most compared phones
605
     *
606
     * @param expEntity
607
     * @param exportPath
608
     * @throws Exception
609
     */
610
    private void getMostComparedProducts(ExpandedEntity expEntity,
611
            String exportPath) throws Exception {
612
        long catalogId = expEntity.getID();
613
 
614
        Map<Long, Long> comparedPhones = CreationUtils.getComparisonStats()
615
                .get(catalogId);
616
 
617
        StringBuffer sb = new StringBuffer();
618
        int maxCount = 10;
619
        int count = 0;
620
        if (comparedPhones != null) {
621
            for (Long entityID : comparedPhones.keySet()) {
622
                if (count > maxCount) {
623
                    break;
624
                }
625
                sb.append(entityID + "\n");
626
                count++;
627
            }
628
        }
629
 
630
        String exportFileName = exportPath + catalogId + File.separator
631
                + "MostComparedProducts.vm";
2733 rajveer 632
        File exportFile = new File(exportFileName);
3929 mandeep.dh 633
        if (!exportFile.exists()) {
2733 rajveer 634
            exportFile.createNewFile();
635
        }
636
 
3929 mandeep.dh 637
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
638
                new FileOutputStream(exportFile)));
639
 
2733 rajveer 640
        writer.write(sb.toString());
641
        writer.flush();
642
        writer.close();
3929 mandeep.dh 643
    }
2733 rajveer 644
 
3929 mandeep.dh 645
    /**
646
     * Get the required parameters for generating velocity content.
647
     *
648
     * @param expEntity
649
     * @return
650
     * @throws Exception
651
     */
652
    private Map<String, String> getEntityParameters(ExpandedEntity expEntity)
653
            throws Exception {
3888 mandeep.dh 654
        Map<String, String> params = new HashMap<String, String>();
655
        String title = EntityUtils.getProductName(expEntity);
656
        String brandName = expEntity.getBrand().trim();
657
        String productName = ((expEntity.getModelName() != null) ? expEntity
658
                .getModelName().trim() + SPACE : "")
659
                + ((expEntity.getModelNumber() != null) ? expEntity
660
                        .getModelNumber().trim() : "");
2171 rajveer 661
 
3888 mandeep.dh 662
        String prodName = title;
663
        if (expEntity.getModelName() != null
664
                && !expEntity.getModelName().isEmpty()
665
                && (expEntity.getBrand().equals("Samsung") || expEntity
666
                        .getBrand().equals("Sony Ericsson"))) {
667
            prodName = expEntity.getBrand().trim()
668
                    + SPACE
669
                    + ((expEntity.getModelName() != null) ? expEntity
670
                            .getModelName().trim() : "");
671
        }
4802 amit.gupta 672
        Category parentCategory = expEntity.getCategory().getParentCategory();
673
 
3888 mandeep.dh 674
        String categoryName = expEntity.getCategory().getLabel();
675
        String tagline = "";
676
        String warranty = "";
677
        String tinySnippet = "";
678
        List<Feature> features = expEntity.getSlide(130054).getFeatures();
679
        for (Feature feature : features) {
680
            if (feature.getFeatureDefinitionID() == 120084) {
681
                PrimitiveDataObject dataObject = (PrimitiveDataObject) feature
682
                        .getBullets().get(0).getDataObject();
683
                tagline = dataObject.getValue();
684
            }
685
            if (feature.getFeatureDefinitionID() == 120089) {
686
                PrimitiveDataObject dataObject = (PrimitiveDataObject) feature
687
                        .getBullets().get(0).getDataObject();
688
                tinySnippet = dataObject.getValue();
689
            }
690
            if (feature.getFeatureDefinitionID() == 120081) {
691
                List<Bullet> bullets = feature.getBullets();
692
                int count = 1;
693
                for (Bullet bullet : bullets) {
694
                    PrimitiveDataObject dataObject = (PrimitiveDataObject) bullet
695
                            .getDataObject();
696
                    params.put("SNIPPET_" + count++, dataObject.getValue());
697
                }
698
            }
699
        }
3869 rajveer 700
 
3888 mandeep.dh 701
        // Creating warranty string!
702
        for (Slide slide : expEntity.getSlide(130054).getChildrenSlides()) {
703
            if (slide.getSlideDefinitionID() == 130105) {
704
                ExpandedSlide expSlide = new ExpandedSlide(slide);
705
                Feature warrantyDurationFeature = expSlide.getExpandedFeature(120125);
706
                if (warrantyDurationFeature != null) {
707
                    ExpandedFeature expFeature = new ExpandedFeature(warrantyDurationFeature);
708
                    ExpandedBullet expBullet = expFeature.getExpandedBullets().get(0);
709
                    if (expBullet != null) {
710
                        String shortForm = expBullet.getUnit().getShortForm();
3869 rajveer 711
 
3888 mandeep.dh 712
                        // Append 's' to month and year
713
                        if (!expBullet.getValue().trim().equals("1")) {
714
                            shortForm += "s";
715
                        }
716
                        warranty += expBullet.getValue() + SPACE + shortForm;
717
                    }
718
                }
3869 rajveer 719
 
3888 mandeep.dh 720
                Feature warrantyTypeFeature = expSlide.getExpandedFeature(120219);
721
                if (warrantyTypeFeature != null) {
722
                    ExpandedFeature expFeature = new ExpandedFeature(warrantyTypeFeature);
723
                    ExpandedBullet expBullet = expFeature.getExpandedBullets().get(0);
724
                    if (expBullet != null) {
725
                        warranty += SPACE + expBullet.getExpandedEnumDataObject()
726
                                        .getEnumValue().getValue();
727
                    }
728
                }
3869 rajveer 729
 
3888 mandeep.dh 730
                Feature warrantyCoverageFeature = expSlide.getExpandedFeature(120220);
731
                if (warrantyCoverageFeature != null) {
732
                    ExpandedFeature expFeature = new ExpandedFeature(warrantyCoverageFeature);
733
                    ExpandedBullet expBullet = expFeature.getExpandedBullets().get(0);
734
                    if (expBullet != null) {
735
                        warranty += SPACE + HYPHON + SPACE + expBullet.getExpandedEnumDataObject().getEnumValue().getValue();
736
                    }
737
                }
738
            }
739
        }
3869 rajveer 740
 
3888 mandeep.dh 741
        long categoryId = expEntity.getCategory().getID();
742
        params.put("PROD_NAME", prodName);
743
        params.put("URL", EntityUtils.getEntityURL(expEntity));
744
        params.put("TITLE", title);
745
        params.put("BRAND_NAME", brandName);
746
        params.put("PRODUCT_NAME", productName);
747
        params.put("CATEGORY_ID", ((int) categoryId) + "");
748
        params.put("CATEGORY_NAME", categoryName);
4926 varun.gupt 749
        params.put("PARENT_CATEGORY", expEntity.getCategory().getParentCategory().getLabel());
3888 mandeep.dh 750
        params.put("CATEGORY_URL", categoryName.replaceAll(SPACE, HYPHON)
751
                .toLowerCase() + "/" + categoryId);
752
        params.put(
753
                "PRODUCT_URL",
754
                URLEncoder.encode("http://www.", "UTF-8")
755
                        + "${domain}"
756
                        + URLEncoder.encode(
757
                                EntityUtils.getEntityURL(expEntity), "UTF-8"));
4036 varun.gupt 758
 
5173 amit.gupta 759
        if (parentCategory.isComparable())	{
4036 varun.gupt 760
        	params.put("IS_COMPARABLE", "TRUE");
761
        } else	{
762
        	params.put("IS_COMPARABLE", "FALSE");
763
        }
764
 
3888 mandeep.dh 765
        params.put("CATALOG_ID", expEntity.getID() + "");
766
        params.put("TAGLINE", tagline);
767
        params.put("WARRANTY", warranty);
768
        params.put("TINY_SNIPPET", tinySnippet);
3929 mandeep.dh 769
        params.put("IMAGE_PREFIX", EntityUtils.getMediaPrefix(expEntity));
3888 mandeep.dh 770
        params.put("contentVersion", contentVersion);
3929 mandeep.dh 771
        params.put("skinImageCreationTime", String.valueOf(EntityUtils.getCreationTimeFromSummarySlide(expEntity, "skin")));
772
        params.put("DEFAULT_IMAGE_SUFFIX", String.valueOf(EntityUtils.getCreationTimeFromSummarySlide(expEntity, "default")));
3888 mandeep.dh 773
 
774
        return params;
775
    }
3929 mandeep.dh 776
 
2171 rajveer 777
 
3929 mandeep.dh 778
    /**
779
     * Generates content for the specified entity embedding links to the
780
     * specified domain name.
781
     *
782
     * The method updates the member variable problems in any of the following
783
     * four cases:
784
     * <ol>
785
     * <li>The entity is not ready.
786
     * <li>The category has not been updated yet. (Set to -1).
787
     * <li>There are no items in the catalog corresponding to this entity.
788
     * <li>There are no active or content-complete items in the catalog
789
     * corresponding to this entity.
790
     * <li>Neither the items have been updated nor the content has been updated.
791
     * </ol>
792
     *
793
     * @param entity
794
     *            - Entity for which the content has to be generated.
795
     * @param domain
796
     *            - The domain name to be used to serve static content.
797
     * @param exportPath
798
     *            - Local file system path where content has to be generated.
799
     * @throws Exception
800
     */
801
    public void generateContentForOneEntity(Entity entity, String exportPath)
802
            throws Exception {
2433 rajveer 803
        ExpandedEntity expEntity = new ExpandedEntity(entity);
3929 mandeep.dh 804
        long catalogId = expEntity.getID();
805
 
806
        // Create new directory
807
        File exportDir = new File(exportPath + catalogId);
808
        if (!exportDir.exists()) {
809
            exportDir.mkdir();
810
        }
811
 
812
        VelocityContext context = new VelocityContext();
813
 
5261 amit.gupta 814
        Category parentCategory = expEntity.getCategory().getParentCategory();
815
        Boolean isComparable = parentCategory.isComparable();
3929 mandeep.dh 816
        String mediaPrefix = EntityUtils.getMediaPrefix(expEntity);
817
        context.put("mediaPrefix", mediaPrefix);
818
        context.put("expentity", expEntity);
819
        context.put("contentVersion", this.contentVersion);
820
        context.put("defs", Catalog.getInstance().getDefinitionsContainer());
2433 rajveer 821
        context.put("helpdocs", CreationUtils.getHelpdocs());
822
        context.put("params", getEntityParameters(expEntity));
5261 amit.gupta 823
        context.put("isComparable", isComparable);
3018 rajveer 824
 
3929 mandeep.dh 825
        List<String> filenames = new ArrayList<String>();
826
        filenames.add("ProductDetail");
827
        filenames.add("WidgetSnippet");
828
        filenames.add("HomeSnippet");
829
        filenames.add("SearchSnippet");
830
        filenames.add("CategorySnippet");
831
        filenames.add("SlideGuide");
832
        filenames.add("MyResearchSnippet");
833
        filenames.add("AfterSales");
4802 amit.gupta 834
 
5261 amit.gupta 835
        if(isComparable){
4802 amit.gupta 836
        	filenames.add("CompareProductSnippet");
837
        	filenames.add("ComparisonSnippet");
838
        	filenames.add("CompareProductSummarySnippet");
5173 amit.gupta 839
        	getMostComparedProducts(expEntity, exportPath);
4802 amit.gupta 840
        	getSlidenamesSnippet(expEntity, exportPath);
3929 mandeep.dh 841
        }
4802 amit.gupta 842
        if(parentCategory.isHasAccessories()){
843
        	getRelatedAccessories(expEntity, exportPath);
844
        }
4906 mandeep.dh 845
        if(parentCategory.getID()==Utils.MOBILE_PHONES_CATAGORY){
4802 amit.gupta 846
        	filenames.add("PhonesIOwnSnippet");
847
        }
848
//        if (expEntity.getCategory().getParentCategory().getID() != Utils.MOBILE_ACCESSORIES_CATEGORY) {
849
//
850
//        	// For laptops we do not have related accessories and most comparable
851
//        	if(expEntity.getCategory().getID() != Utils.LAPTOPS_CATEGORY)	{
852
//                filenames.add("PhonesIOwnSnippet");
853
//
854
//                getRelatedAccessories(expEntity, exportPath);
855
//                getMostComparedProducts(expEntity, exportPath);
856
//        	}
857
//            filenames.add("CompareProductSnippet");
858
//            filenames.add("ComparisonSnippet");
859
//            filenames.add("CompareProductSummarySnippet");
860
//            // This method wont use any velocity file, So calling directly
861
//        }
3929 mandeep.dh 862
 
863
        // This method wont use any velocity file, So calling directly
864
        getProductPropertiesSnippet(expEntity, exportPath);
865
 
866
        applyVelocityTemplate(filenames, exportPath, context, catalogId);
867
 
5263 amit.gupta 868
        generateImages(expEntity, mediaPrefix);
3929 mandeep.dh 869
 
5263 amit.gupta 870
        copyDocuments(expEntity, mediaPrefix);
3929 mandeep.dh 871
    }
872
 
873
    /**
874
     * Get list of files and apply velocity templates on them
875
     *
876
     * @param filenames
877
     * @param exportPath
878
     * @param context
879
     * @param catalogId
880
     */
881
    private void applyVelocityTemplate(List<String> filenames,
882
            String exportPath, VelocityContext context, long catalogId) {
883
        try {
884
            Properties p = new Properties();
885
            p.setProperty("resource.loader", "file");
886
            p.setProperty("file.resource.loader.class",
887
                    "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
888
            p.setProperty("file.resource.loader.path", Utils.VTL_SRC_PATH);
889
            Velocity.init(p);
890
            for (String filename : filenames) {
891
                Template template = Velocity.getTemplate(filename + ".vm");
892
                BufferedWriter writer = new BufferedWriter(
893
                        new OutputStreamWriter(
894
                                new FileOutputStream(exportPath + catalogId
895
                                        + File.separator + filename + ".vm")));
896
                template.merge(context, writer);
897
                writer.flush();
898
                writer.close();
899
            }
900
        } catch (ResourceNotFoundException e) {
901
            log.error("Error generating velocity templates", e);
902
        } catch (IOException e) {
903
            log.error("Error generating velocity templates", e);
904
        } catch (ParseErrorException e) {
905
            log.error("Error generating velocity templates", e);
906
        } catch (Exception e) {
907
            log.error("Error generating velocity templates", e);
908
        }
909
    }
2716 varun.gupt 910
}