Subversion Repositories SmartDukaan

Rev

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