Subversion Repositories SmartDukaan

Rev

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