Subversion Repositories SmartDukaan

Rev

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