Subversion Repositories SmartDukaan

Rev

Rev 5763 | Rev 5945 | 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
 
5930 amit.gupta 395
            Category parentCategory = category.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);
5930 amit.gupta 406
            props.put("compareCategory", parentCategory.isComparable() ? parentCategory.getLabel() : categoryName);
3929 mandeep.dh 407
            props.put("categoryUrl", categoryName.replaceAll(SPACE, "-").toLowerCase() + "/" + category.getID());
408
            String categoryUrl = categoryName.replaceAll(SPACE, "-").toLowerCase() + "/" + category.getID();
409
 
3829 rajveer 410
            String brandUrl = expEntity.getBrand().toLowerCase().replace(' ', '-');
3929 mandeep.dh 411
 
412
            String breadCrumb = "<a href='/'>Home</a>&nbsp;&gt;&nbsp;" +
413
                                "<a href='/" +  categoryUrl + "'>" + categoryName + "</a>&nbsp;&gt;&nbsp;";
3829 rajveer 414
            if(displayAccessories){
3929 mandeep.dh 415
                breadCrumb = breadCrumb +  "<a href='/" + brandUrl + "'>" + expEntity.getBrand() + "</a>";
3829 rajveer 416
            }else{
3929 mandeep.dh 417
                breadCrumb =  breadCrumb + "<a>" + expEntity.getBrand() + "</a>";  
3829 rajveer 418
            }
3929 mandeep.dh 419
            breadCrumb = breadCrumb +  "&nbsp;<a>" + expEntity.getModelName().trim() + SPACE + expEntity.getModelNumber().trim() + "</a>";
3829 rajveer 420
            props.put("breadCrumb", breadCrumb);
3929 mandeep.dh 421
 
422
 
2305 vikas 423
            String exportFileName = exportPath + catalogId + File.separator
2367 rajveer 424
                    + "ProductPropertiesSnippet.vm";
2305 vikas 425
            File exportFile = new File(exportFileName);
426
            if (!exportFile.exists()) {
427
                exportFile.createNewFile();
428
            }
2171 rajveer 429
 
2305 vikas 430
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
431
                    new FileOutputStream(exportFile)));
432
 
433
            writer.write(props.toString());
434
 
435
            writer.flush();
436
            writer.close();
437
        } catch (Exception e) {
3929 mandeep.dh 438
            log.error("Error generating JSON", e);
2305 vikas 439
        }
3929 mandeep.dh 440
    }
2305 vikas 441
 
3929 mandeep.dh 442
    /**
443
     * Get slide names and write them in a file. This file will be used in
444
     * comparison.
445
     *
446
     * @param expEntity
447
     * @param exportPath
448
     * @throws Exception
449
     */
450
    private void getSlidenamesSnippet(ExpandedEntity expEntity,
451
            String exportPath) throws Exception {
452
        long catalogId = expEntity.getID();
2171 rajveer 453
 
3929 mandeep.dh 454
        StringBuilder slideNames = new StringBuilder();
455
 
456
        // TODO Investigate why brand + model number is used ?
457
        slideNames.append(expEntity.getBrand() + SPACE
5322 amit.gupta 458
                + expEntity.getModelName() + SPACE + expEntity.getModelNumber()
3929 mandeep.dh 459
                + "\n");
5048 amit.gupta 460
        slideNames.append(expEntity.getBrand() + SPACE +
5050 amit.gupta 461
        		(StringUtils.isNotEmpty(expEntity.getModelName()) ?  expEntity.getModelName() : expEntity.getModelNumber())
5048 amit.gupta 462
        		+ "\n");
3929 mandeep.dh 463
 
464
        Map<Long, Double> slideScores = CreationUtils
465
                .getSlideComparisonScores(catalogId);
466
 
5930 amit.gupta 467
        DecimalFormat oneDForm = new DecimalFormat("#.#");
3929 mandeep.dh 468
        for (ExpandedSlide expSlide : expEntity.getExpandedSlides()) {
469
            if (expSlide.getSlideDefinitionID() == Utils.SUMMARY_SLIDE_DEFINITION_ID
470
                    || expSlide.getSlideDefinitionID() == Utils.AFTER_SALES_SLIDE_DEFINITION_ID) {
471
                continue;
472
            }
473
            slideNames.append(expSlide.getSlideDefinition().getLabel() + "!!!");
474
 
5930 amit.gupta 475
            String bucketName = Catalog.getInstance().getDefinitionsContainer().getComparisonBucketName(expEntity.getCategoryID(), expSlide.getSlideDefinitionID());
476
            if ( bucketName == null) {
477
                bucketName = "None"; 
3929 mandeep.dh 478
            }
479
            slideNames.append(bucketName + "!!!");
480
 
481
            double score = 0;
5930 amit.gupta 482
            if (slideScores != null && slideScores.get(expSlide.getSlideDefinitionID()) != null) {
3929 mandeep.dh 483
                score = slideScores.get(expSlide.getSlideDefinitionID());
484
            }
485
 
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
        }
5930 amit.gupta 666
        Category cat = expEntity.getCategory();
4802 amit.gupta 667
 
5930 amit.gupta 668
        Category parentCategory = cat.getParentCategory();
669
 
670
        String categoryName = cat.getLabel();
3888 mandeep.dh 671
        String tagline = "";
672
        String warranty = "";
673
        String tinySnippet = "";
674
        List<Feature> features = expEntity.getSlide(130054).getFeatures();
675
        for (Feature feature : features) {
676
            if (feature.getFeatureDefinitionID() == 120084) {
677
                PrimitiveDataObject dataObject = (PrimitiveDataObject) feature
678
                        .getBullets().get(0).getDataObject();
679
                tagline = dataObject.getValue();
680
            }
681
            if (feature.getFeatureDefinitionID() == 120089) {
682
                PrimitiveDataObject dataObject = (PrimitiveDataObject) feature
683
                        .getBullets().get(0).getDataObject();
684
                tinySnippet = dataObject.getValue();
685
            }
686
            if (feature.getFeatureDefinitionID() == 120081) {
687
                List<Bullet> bullets = feature.getBullets();
688
                int count = 1;
689
                for (Bullet bullet : bullets) {
690
                    PrimitiveDataObject dataObject = (PrimitiveDataObject) bullet
691
                            .getDataObject();
692
                    params.put("SNIPPET_" + count++, dataObject.getValue());
693
                }
694
            }
695
        }
3869 rajveer 696
 
3888 mandeep.dh 697
        // Creating warranty string!
698
        for (Slide slide : expEntity.getSlide(130054).getChildrenSlides()) {
699
            if (slide.getSlideDefinitionID() == 130105) {
700
                ExpandedSlide expSlide = new ExpandedSlide(slide);
701
                Feature warrantyDurationFeature = expSlide.getExpandedFeature(120125);
702
                if (warrantyDurationFeature != null) {
703
                    ExpandedFeature expFeature = new ExpandedFeature(warrantyDurationFeature);
704
                    ExpandedBullet expBullet = expFeature.getExpandedBullets().get(0);
705
                    if (expBullet != null) {
706
                        String shortForm = expBullet.getUnit().getShortForm();
3869 rajveer 707
 
3888 mandeep.dh 708
                        // Append 's' to month and year
709
                        if (!expBullet.getValue().trim().equals("1")) {
710
                            shortForm += "s";
711
                        }
712
                        warranty += expBullet.getValue() + SPACE + shortForm;
713
                    }
714
                }
3869 rajveer 715
 
3888 mandeep.dh 716
                Feature warrantyTypeFeature = expSlide.getExpandedFeature(120219);
717
                if (warrantyTypeFeature != null) {
718
                    ExpandedFeature expFeature = new ExpandedFeature(warrantyTypeFeature);
719
                    ExpandedBullet expBullet = expFeature.getExpandedBullets().get(0);
720
                    if (expBullet != null) {
721
                        warranty += SPACE + expBullet.getExpandedEnumDataObject()
722
                                        .getEnumValue().getValue();
723
                    }
724
                }
3869 rajveer 725
 
3888 mandeep.dh 726
                Feature warrantyCoverageFeature = expSlide.getExpandedFeature(120220);
727
                if (warrantyCoverageFeature != null) {
728
                    ExpandedFeature expFeature = new ExpandedFeature(warrantyCoverageFeature);
729
                    ExpandedBullet expBullet = expFeature.getExpandedBullets().get(0);
730
                    if (expBullet != null) {
731
                        warranty += SPACE + HYPHON + SPACE + expBullet.getExpandedEnumDataObject().getEnumValue().getValue();
732
                    }
733
                }
734
            }
735
        }
5930 amit.gupta 736
        long categoryId = cat.getID();
3888 mandeep.dh 737
        params.put("PROD_NAME", prodName);
738
        params.put("URL", EntityUtils.getEntityURL(expEntity));
739
        params.put("TITLE", title);
740
        params.put("BRAND_NAME", brandName);
741
        params.put("PRODUCT_NAME", productName);
742
        params.put("CATEGORY_ID", ((int) categoryId) + "");
743
        params.put("CATEGORY_NAME", categoryName);
5930 amit.gupta 744
        params.put("PARENT_CATEGORY", parentCategory.getLabel());
745
        params.put("COMPARE_CATEGORY", parentCategory.isComparable() ? 
746
        			parentCategory.getLabel(): cat.getLabel());
3888 mandeep.dh 747
        params.put("CATEGORY_URL", categoryName.replaceAll(SPACE, HYPHON)
748
                .toLowerCase() + "/" + categoryId);
749
        params.put(
750
                "PRODUCT_URL",
751
                URLEncoder.encode("http://www.", "UTF-8")
752
                        + "${domain}"
753
                        + URLEncoder.encode(
754
                                EntityUtils.getEntityURL(expEntity), "UTF-8"));
4036 varun.gupt 755
 
5930 amit.gupta 756
        if (cat.isComparable())	{
4036 varun.gupt 757
        	params.put("IS_COMPARABLE", "TRUE");
758
        } else	{
759
        	params.put("IS_COMPARABLE", "FALSE");
760
        }
761
 
3888 mandeep.dh 762
        params.put("CATALOG_ID", expEntity.getID() + "");
763
        params.put("TAGLINE", tagline);
764
        params.put("WARRANTY", warranty);
765
        params.put("TINY_SNIPPET", tinySnippet);
3929 mandeep.dh 766
        params.put("IMAGE_PREFIX", EntityUtils.getMediaPrefix(expEntity));
3888 mandeep.dh 767
        params.put("contentVersion", contentVersion);
3929 mandeep.dh 768
        params.put("skinImageCreationTime", String.valueOf(EntityUtils.getCreationTimeFromSummarySlide(expEntity, "skin")));
769
        params.put("DEFAULT_IMAGE_SUFFIX", String.valueOf(EntityUtils.getCreationTimeFromSummarySlide(expEntity, "default")));
3888 mandeep.dh 770
 
771
        return params;
772
    }
3929 mandeep.dh 773
 
2171 rajveer 774
 
3929 mandeep.dh 775
    /**
776
     * Generates content for the specified entity embedding links to the
777
     * specified domain name.
778
     *
779
     * The method updates the member variable problems in any of the following
780
     * four cases:
781
     * <ol>
782
     * <li>The entity is not ready.
783
     * <li>The category has not been updated yet. (Set to -1).
784
     * <li>There are no items in the catalog corresponding to this entity.
785
     * <li>There are no active or content-complete items in the catalog
786
     * corresponding to this entity.
787
     * <li>Neither the items have been updated nor the content has been updated.
788
     * </ol>
789
     *
790
     * @param entity
791
     *            - Entity for which the content has to be generated.
792
     * @param domain
793
     *            - The domain name to be used to serve static content.
794
     * @param exportPath
795
     *            - Local file system path where content has to be generated.
796
     * @throws Exception
797
     */
798
    public void generateContentForOneEntity(Entity entity, String exportPath)
799
            throws Exception {
2433 rajveer 800
        ExpandedEntity expEntity = new ExpandedEntity(entity);
3929 mandeep.dh 801
        long catalogId = expEntity.getID();
802
 
803
        // Create new directory
804
        File exportDir = new File(exportPath + catalogId);
805
        if (!exportDir.exists()) {
806
            exportDir.mkdir();
807
        }
808
 
809
        VelocityContext context = new VelocityContext();
810
 
5261 amit.gupta 811
        Category parentCategory = expEntity.getCategory().getParentCategory();
5930 amit.gupta 812
        Boolean isComparable = expEntity.getCategory().isComparable();
3929 mandeep.dh 813
        String mediaPrefix = EntityUtils.getMediaPrefix(expEntity);
814
        context.put("mediaPrefix", mediaPrefix);
815
        context.put("expentity", expEntity);
816
        context.put("contentVersion", this.contentVersion);
817
        context.put("defs", Catalog.getInstance().getDefinitionsContainer());
2433 rajveer 818
        context.put("helpdocs", CreationUtils.getHelpdocs());
819
        context.put("params", getEntityParameters(expEntity));
5261 amit.gupta 820
        context.put("isComparable", isComparable);
3018 rajveer 821
 
3929 mandeep.dh 822
        List<String> filenames = new ArrayList<String>();
823
        filenames.add("ProductDetail");
824
        filenames.add("WidgetSnippet");
825
        filenames.add("HomeSnippet");
826
        filenames.add("SearchSnippet");
827
        filenames.add("CategorySnippet");
828
        filenames.add("SlideGuide");
5930 amit.gupta 829
        filenames.add("AfterSales");
830
        filenames.add("CompareProductSnippet");
831
        filenames.add("ComparisonSnippet");
832
        getSlidenamesSnippet(expEntity, exportPath);
3929 mandeep.dh 833
        filenames.add("MyResearchSnippet");
5261 amit.gupta 834
        if(isComparable){
4802 amit.gupta 835
        	filenames.add("CompareProductSummarySnippet");
5552 phani.kuma 836
        	filenames.add("MostComparedSnippet");
5173 amit.gupta 837
        	getMostComparedProducts(expEntity, exportPath);
3929 mandeep.dh 838
        }
4802 amit.gupta 839
        if(parentCategory.isHasAccessories()){
840
        	getRelatedAccessories(expEntity, exportPath);
841
        }
4906 mandeep.dh 842
        if(parentCategory.getID()==Utils.MOBILE_PHONES_CATAGORY){
4802 amit.gupta 843
        	filenames.add("PhonesIOwnSnippet");
844
        }
845
//        if (expEntity.getCategory().getParentCategory().getID() != Utils.MOBILE_ACCESSORIES_CATEGORY) {
846
//
847
//        	// For laptops we do not have related accessories and most comparable
848
//        	if(expEntity.getCategory().getID() != Utils.LAPTOPS_CATEGORY)	{
849
//                filenames.add("PhonesIOwnSnippet");
850
//
851
//                getRelatedAccessories(expEntity, exportPath);
852
//                getMostComparedProducts(expEntity, exportPath);
853
//        	}
854
//            filenames.add("CompareProductSnippet");
855
//            filenames.add("ComparisonSnippet");
856
//            filenames.add("CompareProductSummarySnippet");
857
//            // This method wont use any velocity file, So calling directly
858
//        }
3929 mandeep.dh 859
 
860
        // This method wont use any velocity file, So calling directly
861
        getProductPropertiesSnippet(expEntity, exportPath);
862
 
863
        applyVelocityTemplate(filenames, exportPath, context, catalogId);
864
 
5263 amit.gupta 865
        generateImages(expEntity, mediaPrefix);
3929 mandeep.dh 866
 
5263 amit.gupta 867
        copyDocuments(expEntity, mediaPrefix);
3929 mandeep.dh 868
    }
869
 
870
    /**
871
     * Get list of files and apply velocity templates on them
872
     *
873
     * @param filenames
874
     * @param exportPath
875
     * @param context
876
     * @param catalogId
877
     */
878
    private void applyVelocityTemplate(List<String> filenames,
879
            String exportPath, VelocityContext context, long catalogId) {
880
        try {
881
            Properties p = new Properties();
882
            p.setProperty("resource.loader", "file");
883
            p.setProperty("file.resource.loader.class",
884
                    "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
885
            p.setProperty("file.resource.loader.path", Utils.VTL_SRC_PATH);
886
            Velocity.init(p);
887
            for (String filename : filenames) {
888
                Template template = Velocity.getTemplate(filename + ".vm");
889
                BufferedWriter writer = new BufferedWriter(
890
                        new OutputStreamWriter(
891
                                new FileOutputStream(exportPath + catalogId
892
                                        + File.separator + filename + ".vm")));
893
                template.merge(context, writer);
894
                writer.flush();
895
                writer.close();
896
            }
897
        } catch (ResourceNotFoundException e) {
898
            log.error("Error generating velocity templates", e);
899
        } catch (IOException e) {
900
            log.error("Error generating velocity templates", e);
901
        } catch (ParseErrorException e) {
902
            log.error("Error generating velocity templates", e);
903
        } catch (Exception e) {
904
            log.error("Error generating velocity templates", e);
905
        }
906
    }
2716 varun.gupt 907
}