Subversion Repositories SmartDukaan

Rev

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