Subversion Repositories SmartDukaan

Rev

Rev 7814 | Rev 9280 | 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 {
9218 amit.gupta 63
    public static final String ICON_JPG = "icon.jpg";
64
    public static final String THUMBNAIL_JPG = "thumbnail.jpg";
65
    public 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
 
9218 amit.gupta 611
        Map<Long, Long> comparedPhones = CreationUtils.getComparisonStats().get(catalogId);
3929 mandeep.dh 612
 
613
        StringBuffer sb = new StringBuffer();
614
        int maxCount = 10;
615
        int count = 0;
616
        if (comparedPhones != null) {
617
            for (Long entityID : comparedPhones.keySet()) {
618
                if (count > maxCount) {
619
                    break;
620
                }
621
                sb.append(entityID + "\n");
622
                count++;
623
            }
624
        }
625
 
626
        String exportFileName = exportPath + catalogId + File.separator
627
                + "MostComparedProducts.vm";
2733 rajveer 628
        File exportFile = new File(exportFileName);
3929 mandeep.dh 629
        if (!exportFile.exists()) {
2733 rajveer 630
            exportFile.createNewFile();
631
        }
632
 
3929 mandeep.dh 633
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
634
                new FileOutputStream(exportFile)));
635
 
2733 rajveer 636
        writer.write(sb.toString());
637
        writer.flush();
638
        writer.close();
3929 mandeep.dh 639
    }
2733 rajveer 640
 
3929 mandeep.dh 641
    /**
642
     * Get the required parameters for generating velocity content.
643
     *
644
     * @param expEntity
645
     * @return
646
     * @throws Exception
647
     */
648
    private Map<String, String> getEntityParameters(ExpandedEntity expEntity)
649
            throws Exception {
3888 mandeep.dh 650
        Map<String, String> params = new HashMap<String, String>();
651
        String title = EntityUtils.getProductName(expEntity);
652
        String brandName = expEntity.getBrand().trim();
653
        String productName = ((expEntity.getModelName() != null) ? expEntity
654
                .getModelName().trim() + SPACE : "")
655
                + ((expEntity.getModelNumber() != null) ? expEntity
656
                        .getModelNumber().trim() : "");
2171 rajveer 657
 
3888 mandeep.dh 658
        String prodName = title;
659
        if (expEntity.getModelName() != null
660
                && !expEntity.getModelName().isEmpty()
661
                && (expEntity.getBrand().equals("Samsung") || expEntity
662
                        .getBrand().equals("Sony Ericsson"))) {
663
            prodName = expEntity.getBrand().trim()
664
                    + SPACE
665
                    + ((expEntity.getModelName() != null) ? expEntity
666
                            .getModelName().trim() : "");
667
        }
5930 amit.gupta 668
        Category cat = expEntity.getCategory();
4802 amit.gupta 669
 
5930 amit.gupta 670
        Category parentCategory = cat.getParentCategory();
671
 
672
        String categoryName = cat.getLabel();
3888 mandeep.dh 673
        String tagline = "";
674
        String warranty = "";
675
        String tinySnippet = "";
676
        List<Feature> features = expEntity.getSlide(130054).getFeatures();
677
        for (Feature feature : features) {
678
            if (feature.getFeatureDefinitionID() == 120084) {
679
                PrimitiveDataObject dataObject = (PrimitiveDataObject) feature
680
                        .getBullets().get(0).getDataObject();
681
                tagline = dataObject.getValue();
682
            }
683
            if (feature.getFeatureDefinitionID() == 120089) {
684
                PrimitiveDataObject dataObject = (PrimitiveDataObject) feature
685
                        .getBullets().get(0).getDataObject();
686
                tinySnippet = dataObject.getValue();
687
            }
688
            if (feature.getFeatureDefinitionID() == 120081) {
689
                List<Bullet> bullets = feature.getBullets();
690
                int count = 1;
691
                for (Bullet bullet : bullets) {
692
                    PrimitiveDataObject dataObject = (PrimitiveDataObject) bullet
693
                            .getDataObject();
694
                    params.put("SNIPPET_" + count++, dataObject.getValue());
695
                }
696
            }
697
        }
3869 rajveer 698
 
3888 mandeep.dh 699
        // Creating warranty string!
700
        for (Slide slide : expEntity.getSlide(130054).getChildrenSlides()) {
701
            if (slide.getSlideDefinitionID() == 130105) {
702
                ExpandedSlide expSlide = new ExpandedSlide(slide);
703
                Feature warrantyDurationFeature = expSlide.getExpandedFeature(120125);
704
                if (warrantyDurationFeature != null) {
705
                    ExpandedFeature expFeature = new ExpandedFeature(warrantyDurationFeature);
706
                    ExpandedBullet expBullet = expFeature.getExpandedBullets().get(0);
707
                    if (expBullet != null) {
708
                        String shortForm = expBullet.getUnit().getShortForm();
3869 rajveer 709
 
3888 mandeep.dh 710
                        // Append 's' to month and year
711
                        if (!expBullet.getValue().trim().equals("1")) {
712
                            shortForm += "s";
713
                        }
714
                        warranty += expBullet.getValue() + SPACE + shortForm;
715
                    }
716
                }
3869 rajveer 717
 
3888 mandeep.dh 718
                Feature warrantyTypeFeature = expSlide.getExpandedFeature(120219);
719
                if (warrantyTypeFeature != null) {
720
                    ExpandedFeature expFeature = new ExpandedFeature(warrantyTypeFeature);
721
                    ExpandedBullet expBullet = expFeature.getExpandedBullets().get(0);
722
                    if (expBullet != null) {
723
                        warranty += SPACE + expBullet.getExpandedEnumDataObject()
724
                                        .getEnumValue().getValue();
725
                    }
726
                }
3869 rajveer 727
 
3888 mandeep.dh 728
                Feature warrantyCoverageFeature = expSlide.getExpandedFeature(120220);
729
                if (warrantyCoverageFeature != null) {
730
                    ExpandedFeature expFeature = new ExpandedFeature(warrantyCoverageFeature);
731
                    ExpandedBullet expBullet = expFeature.getExpandedBullets().get(0);
732
                    if (expBullet != null) {
733
                        warranty += SPACE + HYPHON + SPACE + expBullet.getExpandedEnumDataObject().getEnumValue().getValue();
734
                    }
735
                }
736
            }
737
        }
5930 amit.gupta 738
        long categoryId = cat.getID();
3888 mandeep.dh 739
        params.put("PROD_NAME", prodName);
740
        params.put("URL", EntityUtils.getEntityURL(expEntity));
741
        params.put("TITLE", title);
742
        params.put("BRAND_NAME", brandName);
743
        params.put("PRODUCT_NAME", productName);
744
        params.put("CATEGORY_ID", ((int) categoryId) + "");
745
        params.put("CATEGORY_NAME", categoryName);
5930 amit.gupta 746
        params.put("PARENT_CATEGORY", parentCategory.getLabel());
747
        params.put("COMPARE_CATEGORY", parentCategory.isComparable() ? 
748
        			parentCategory.getLabel(): cat.getLabel());
3888 mandeep.dh 749
        params.put("CATEGORY_URL", categoryName.replaceAll(SPACE, HYPHON)
750
                .toLowerCase() + "/" + categoryId);
751
        params.put(
752
                "PRODUCT_URL",
753
                URLEncoder.encode("http://www.", "UTF-8")
754
                        + "${domain}"
755
                        + URLEncoder.encode(
756
                                EntityUtils.getEntityURL(expEntity), "UTF-8"));
4036 varun.gupt 757
 
5930 amit.gupta 758
        if (cat.isComparable())	{
4036 varun.gupt 759
        	params.put("IS_COMPARABLE", "TRUE");
760
        } else	{
761
        	params.put("IS_COMPARABLE", "FALSE");
762
        }
763
 
3888 mandeep.dh 764
        params.put("CATALOG_ID", expEntity.getID() + "");
765
        params.put("TAGLINE", tagline);
766
        params.put("WARRANTY", warranty);
767
        params.put("TINY_SNIPPET", tinySnippet);
3929 mandeep.dh 768
        params.put("IMAGE_PREFIX", EntityUtils.getMediaPrefix(expEntity));
3888 mandeep.dh 769
        params.put("contentVersion", contentVersion);
3929 mandeep.dh 770
        params.put("skinImageCreationTime", String.valueOf(EntityUtils.getCreationTimeFromSummarySlide(expEntity, "skin")));
771
        params.put("DEFAULT_IMAGE_SUFFIX", String.valueOf(EntityUtils.getCreationTimeFromSummarySlide(expEntity, "default")));
3888 mandeep.dh 772
 
773
        return params;
774
    }
3929 mandeep.dh 775
 
2171 rajveer 776
 
3929 mandeep.dh 777
    /**
778
     * Generates content for the specified entity embedding links to the
779
     * specified domain name.
780
     *
781
     * The method updates the member variable problems in any of the following
782
     * four cases:
783
     * <ol>
784
     * <li>The entity is not ready.
785
     * <li>The category has not been updated yet. (Set to -1).
786
     * <li>There are no items in the catalog corresponding to this entity.
787
     * <li>There are no active or content-complete items in the catalog
788
     * corresponding to this entity.
789
     * <li>Neither the items have been updated nor the content has been updated.
790
     * </ol>
791
     *
792
     * @param entity
793
     *            - Entity for which the content has to be generated.
794
     * @param domain
795
     *            - The domain name to be used to serve static content.
796
     * @param exportPath
797
     *            - Local file system path where content has to be generated.
798
     * @throws Exception
799
     */
800
    public void generateContentForOneEntity(Entity entity, String exportPath)
801
            throws Exception {
2433 rajveer 802
        ExpandedEntity expEntity = new ExpandedEntity(entity);
3929 mandeep.dh 803
        long catalogId = expEntity.getID();
804
 
805
        // Create new directory
806
        File exportDir = new File(exportPath + catalogId);
807
        if (!exportDir.exists()) {
808
            exportDir.mkdir();
809
        }
7814 amit.gupta 810
        File storeDir = new File(exportPath + "store/" + catalogId);
811
        if (!storeDir.exists()) {
812
        	storeDir.mkdir();
813
        }
3929 mandeep.dh 814
 
815
        VelocityContext context = new VelocityContext();
816
 
5261 amit.gupta 817
        Category parentCategory = expEntity.getCategory().getParentCategory();
5930 amit.gupta 818
        Boolean isComparable = expEntity.getCategory().isComparable();
3929 mandeep.dh 819
        String mediaPrefix = EntityUtils.getMediaPrefix(expEntity);
820
        context.put("mediaPrefix", mediaPrefix);
821
        context.put("expentity", expEntity);
822
        context.put("contentVersion", this.contentVersion);
823
        context.put("defs", Catalog.getInstance().getDefinitionsContainer());
2433 rajveer 824
        context.put("helpdocs", CreationUtils.getHelpdocs());
825
        context.put("params", getEntityParameters(expEntity));
5261 amit.gupta 826
        context.put("isComparable", isComparable);
7525 amit.gupta 827
        context.put("expertReviews", getExpertReviews(catalogId));
3018 rajveer 828
 
3929 mandeep.dh 829
        List<String> filenames = new ArrayList<String>();
830
        filenames.add("ProductDetail");
7814 amit.gupta 831
        filenames.add("store/ProductDetail");
3929 mandeep.dh 832
        filenames.add("WidgetSnippet");
833
        filenames.add("HomeSnippet");
7814 amit.gupta 834
        filenames.add("store/HomeSnippet");
3929 mandeep.dh 835
        filenames.add("SearchSnippet");
7814 amit.gupta 836
        filenames.add("store/SearchSnippet");
3929 mandeep.dh 837
        filenames.add("CategorySnippet");
7814 amit.gupta 838
        filenames.add("store/CategorySnippet");
3929 mandeep.dh 839
        filenames.add("SlideGuide");
7814 amit.gupta 840
        filenames.add("store/SlideGuide");
5930 amit.gupta 841
        filenames.add("AfterSales");
842
        filenames.add("CompareProductSnippet");
843
        filenames.add("ComparisonSnippet");
844
        getSlidenamesSnippet(expEntity, exportPath);
3929 mandeep.dh 845
        filenames.add("MyResearchSnippet");
5261 amit.gupta 846
        if(isComparable){
4802 amit.gupta 847
        	filenames.add("CompareProductSummarySnippet");
5552 phani.kuma 848
        	filenames.add("MostComparedSnippet");
5173 amit.gupta 849
        	getMostComparedProducts(expEntity, exportPath);
3929 mandeep.dh 850
        }
4802 amit.gupta 851
        if(parentCategory.isHasAccessories()){
852
        	getRelatedAccessories(expEntity, exportPath);
853
        }
4906 mandeep.dh 854
        if(parentCategory.getID()==Utils.MOBILE_PHONES_CATAGORY){
4802 amit.gupta 855
        	filenames.add("PhonesIOwnSnippet");
856
        }
857
//        if (expEntity.getCategory().getParentCategory().getID() != Utils.MOBILE_ACCESSORIES_CATEGORY) {
858
//
859
//        	// For laptops we do not have related accessories and most comparable
860
//        	if(expEntity.getCategory().getID() != Utils.LAPTOPS_CATEGORY)	{
861
//                filenames.add("PhonesIOwnSnippet");
862
//
863
//                getRelatedAccessories(expEntity, exportPath);
864
//                getMostComparedProducts(expEntity, exportPath);
865
//        	}
866
//            filenames.add("CompareProductSnippet");
867
//            filenames.add("ComparisonSnippet");
868
//            filenames.add("CompareProductSummarySnippet");
869
//            // This method wont use any velocity file, So calling directly
870
//        }
3929 mandeep.dh 871
 
872
        // This method wont use any velocity file, So calling directly
873
        getProductPropertiesSnippet(expEntity, exportPath);
874
 
875
        applyVelocityTemplate(filenames, exportPath, context, catalogId);
876
 
5263 amit.gupta 877
        generateImages(expEntity, mediaPrefix);
3929 mandeep.dh 878
 
5263 amit.gupta 879
        copyDocuments(expEntity, mediaPrefix);
3929 mandeep.dh 880
    }
881
 
7525 amit.gupta 882
    private List<ExpertReview> getExpertReviews(long catalogId) throws Exception {
883
		List<ExpertReview> expertReviews = CreationUtils.getExpertReviewByEntity(catalogId);
884
		if(expertReviews != null) {
885
			Iterator<ExpertReview> iter = expertReviews.iterator();
886
			while (iter.hasNext()){
887
				ExpertReview er = iter.next();
888
				if(!er.getStatus().equals(ExpertReviewStatus.PUBLISHED)){
889
					iter.remove();
890
				}
891
			}
892
			if(expertReviews.size()==0){
893
				expertReviews = null;
894
			}
895
 
896
		}
897
		return expertReviews;
898
	}
899
 
900
	/**
3929 mandeep.dh 901
     * Get list of files and apply velocity templates on them
902
     *
903
     * @param filenames
904
     * @param exportPath
905
     * @param context
906
     * @param catalogId
907
     */
908
    private void applyVelocityTemplate(List<String> filenames,
909
            String exportPath, VelocityContext context, long catalogId) {
910
        try {
911
            Properties p = new Properties();
912
            p.setProperty("resource.loader", "file");
913
            p.setProperty("file.resource.loader.class",
914
                    "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
915
            p.setProperty("file.resource.loader.path", Utils.VTL_SRC_PATH);
916
            Velocity.init(p);
917
            for (String filename : filenames) {
918
                Template template = Velocity.getTemplate(filename + ".vm");
919
                BufferedWriter writer = new BufferedWriter(
920
                        new OutputStreamWriter(
7814 amit.gupta 921
                                new FileOutputStream(exportPath + (filename.contains("store/")? "store/" : "") + catalogId
922
                                        + File.separator + (filename.contains("store/")? filename.split("/")[1] : filename) + ".vm")));
3929 mandeep.dh 923
                template.merge(context, writer);
924
                writer.flush();
925
                writer.close();
926
            }
927
        } catch (ResourceNotFoundException e) {
928
            log.error("Error generating velocity templates", e);
929
        } catch (IOException e) {
930
            log.error("Error generating velocity templates", e);
931
        } catch (ParseErrorException e) {
932
            log.error("Error generating velocity templates", e);
933
        } catch (Exception e) {
934
            log.error("Error generating velocity templates", e);
935
        }
936
    }
2716 varun.gupt 937
}