Subversion Repositories SmartDukaan

Rev

Rev 3889 | Rev 3945 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 3889 Rev 3929
Line 1... Line 1...
1
package in.shop2020.ui.util;
1
package in.shop2020.ui.util;
2
 
2
 
3
import in.shop2020.metamodel.core.Bullet;
3
import in.shop2020.metamodel.core.Bullet;
4
import in.shop2020.metamodel.core.Entity;
4
import in.shop2020.metamodel.core.Entity;
5
import in.shop2020.metamodel.core.Feature;
5
import in.shop2020.metamodel.core.Feature;
-
 
6
import in.shop2020.metamodel.core.FreeformContent;
6
import in.shop2020.metamodel.core.Media;
7
import in.shop2020.metamodel.core.Media;
7
import in.shop2020.metamodel.core.PrimitiveDataObject;
8
import in.shop2020.metamodel.core.PrimitiveDataObject;
8
import in.shop2020.metamodel.core.Slide;
9
import in.shop2020.metamodel.core.Slide;
9
import in.shop2020.metamodel.definitions.Catalog;
10
import in.shop2020.metamodel.definitions.Catalog;
10
import in.shop2020.metamodel.definitions.Category;
11
import in.shop2020.metamodel.definitions.Category;
Line 18... Line 19...
18
 
19
 
19
import java.io.BufferedWriter;
20
import java.io.BufferedWriter;
20
import java.io.File;
21
import java.io.File;
21
import java.io.FileInputStream;
22
import java.io.FileInputStream;
22
import java.io.FileOutputStream;
23
import java.io.FileOutputStream;
-
 
24
import java.io.FilenameFilter;
23
import java.io.IOException;
25
import java.io.IOException;
24
import java.io.InputStream;
-
 
25
import java.io.OutputStream;
-
 
26
import java.io.OutputStreamWriter;
26
import java.io.OutputStreamWriter;
27
import java.net.URLEncoder;
27
import java.net.URLEncoder;
-
 
28
import java.nio.channels.FileChannel;
28
import java.text.DecimalFormat;
29
import java.text.DecimalFormat;
29
import java.util.ArrayList;
30
import java.util.ArrayList;
30
import java.util.HashMap;
31
import java.util.HashMap;
31
import java.util.List;
32
import java.util.List;
32
import java.util.Map;
33
import java.util.Map;
33
import java.util.Properties;
34
import java.util.Properties;
34
 
35
 
-
 
36
import org.apache.commons.logging.Log;
-
 
37
import org.apache.commons.logging.LogFactory;
35
import org.apache.velocity.Template;
38
import org.apache.velocity.Template;
36
import org.apache.velocity.VelocityContext;
39
import org.apache.velocity.VelocityContext;
37
import org.apache.velocity.app.Velocity;
40
import org.apache.velocity.app.Velocity;
38
import org.apache.velocity.exception.ParseErrorException;
41
import org.apache.velocity.exception.ParseErrorException;
39
import org.apache.velocity.exception.ResourceNotFoundException;
42
import org.apache.velocity.exception.ResourceNotFoundException;
40
import org.json.JSONObject;
43
import org.json.JSONObject;
41
 
44
 
42
/**
45
/**
43
 * Utility class to merge Java data objects with VTL scripts.
46
 * Utility class to merge Java data objects with VTL scripts. Also generates
44
 * Also generates images and other required stuff for rendering content
47
 * images and other required stuff for rendering content
45
 * 
48
 *
46
 * @author rajveer
49
 * @author rajveer
47
 *
50
 *
48
 */
51
 */
49
public class NewVUI {
52
public class NewVUI {
-
 
53
    private static final String ICON_JPG = "icon.jpg";
-
 
54
    private static final String THUMBNAIL_JPG = "thumbnail.jpg";
-
 
55
    private static final String DEFAULT_JPG = "default.jpg";
50
    private static final String SPACE = " ";
56
    private static final String SPACE = " ";
-
 
57
    private static final String DOT = ".";
-
 
58
    private static final String ESCAPED_DOT = "\\.";
51
    private static final String HYPHON = "-";
59
    private static final String HYPHON = "-";
-
 
60
    private static Log log = LogFactory.getLog(NewVUI.class);
-
 
61
    private String     contentVersion;
52
 
62
 
53
	String contentVersion;  
63
    public NewVUI(Long contentVersion) throws Exception {
-
 
64
        this.contentVersion = contentVersion.toString();
-
 
65
    }
54
 
66
 
55
	public NewVUI(Long contentVersion) throws Exception {
-
 
56
		this.contentVersion = contentVersion.toString();
-
 
57
	}
-
 
58
 
-
 
59
	/**
-
 
60
	 * Utility method to delete a directory.
-
 
61
	 * @param dir
-
 
62
	 * @return
-
 
63
	 */
-
 
64
	private boolean deleteDir(File dir) {
-
 
65
	    if (dir.isDirectory()) {
-
 
66
	        String[] children = dir.list();
-
 
67
	        for (int i=0; i<children.length; i++) {
-
 
68
	            boolean success = deleteDir(new File(dir, children[i]));
-
 
69
	            if (!success) {
-
 
70
	                return false;
-
 
71
	            }
-
 
72
	        }
-
 
73
	    }
-
 
74
	    // The directory is now empty so delete it
-
 
75
	    return dir.delete();
-
 
76
	}
-
 
77
	
-
 
78
	/**
-
 
79
	 * Delete old resources of the entity for which content needs to be regenerated  
-
 
80
	 * @param mediaPath
-
 
81
	 * @param contentPath
-
 
82
	 */
-
 
83
	private void deleteOldResources(String mediaPath, String contentPath) {
-
 
84
		File f = new File(contentPath);
-
 
85
		if(f.exists()){
-
 
86
			deleteDir(f);
-
 
87
		}
-
 
88
		
-
 
89
		f = new File(mediaPath);
-
 
90
		if(f.exists()){
-
 
91
			deleteDir(f);
-
 
92
		}
-
 
93
	}
-
 
94
 
-
 
95
	
-
 
96
	private void copyDocuments(ExpandedEntity expEntity) throws IOException {
67
    private void copyDocuments(ExpandedEntity expEntity, String documentPrefix) throws IOException {
97
		long catalogId = expEntity.getID();
-
 
98
		String sourceDirectory = Utils.CONTENT_DB_PATH + "media" + File.separator + catalogId;
-
 
99
		String destinationDirectory = Utils.EXPORT_PATH + "documents" + File.separator + catalogId;
-
 
100
		
-
 
101
		/*
-
 
102
		 * Create the directory for this entity if it didn't exist.
-
 
103
		 */
-
 
104
		File destFile = new File(destinationDirectory);
-
 
105
		if (!destFile.exists()) {
-
 
106
			destFile.mkdir();
-
 
107
		}
-
 
108
		
-
 
109
		ExpandedSlide expSlide = expEntity.getExpandedSlide(Utils.AFTER_SALES_SLIDE_DEFINITION_ID);
-
 
110
		if(expSlide == null || expSlide.getFreeformContent()==null){
-
 
111
			return;
-
 
112
		}
-
 
113
		Map<String, Media> medias = expSlide.getFreeformContent().getMedias();
-
 
114
		List<String> documentLabels = expSlide.getFreeformContent().getDocumentLabels();
-
 
115
		if((documentLabels == null || documentLabels.isEmpty())){
-
 
116
			return;
-
 
117
		}else{
-
 
118
			for(String documentLabel: documentLabels){
-
 
119
				Media document = medias.get(documentLabel);
-
 
120
				String fileName = document.getFileName();
-
 
121
				copyFile(sourceDirectory + File.separator + fileName, destinationDirectory + File.separator + fileName);
-
 
122
			}
-
 
123
		}
-
 
124
	}
-
 
125
 
-
 
126
	
-
 
127
	/**
-
 
128
	 * It Actually copies the images from some given directory to export directory.
-
 
129
	 * It also attaches the imagePrefix at the end of image name. 
-
 
130
	 * @param catalogId
-
 
131
	 * @param imagePrefix
-
 
132
	 * @throws IOException
-
 
133
	 */
-
 
134
	private void generateImages(long catalogId, String imagePrefix) throws IOException {
-
 
135
		String globalImageDirPath = Utils.CONTENT_DB_PATH + "media" + File.separator;
-
 
136
		String globalDefaultImagePath = globalImageDirPath + "default.jpg";
-
 
137
 
-
 
138
		String imageDirPath = globalImageDirPath + catalogId + File.separator;
-
 
139
		String defaultImagePath = imageDirPath + "default.jpg";
-
 
140
 
-
 
141
		/*
-
 
142
		 * Create the directory for this entity if it didn't exist.
-
 
143
		 */
-
 
144
		File f = new File(globalImageDirPath + catalogId);
-
 
145
		if (!f.exists()) {
-
 
146
			f.mkdir();
-
 
147
		}
-
 
148
 
-
 
149
		/*
-
 
150
		 * If the default image is not present for this entity, copy the global
-
 
151
		 * default image.
-
 
152
		 * TODO: This part will be moved to the Jython Script
-
 
153
		 */
-
 
154
		File f3 = new File(defaultImagePath);
-
 
155
		if (!f3.exists()) {
-
 
156
		        copyFile(globalDefaultImagePath, defaultImagePath);
-
 
157
		    }
-
 
158
 
-
 
159
		String exportPath = Utils.EXPORT_MEDIA_PATH + catalogId;
-
 
160
		/*
-
 
161
		 * Copying the generated content from db/media to export/media. This
-
 
162
		 * will also insert a timestamp tag in the file names.
-
 
163
		 */
-
 
164
		File sourceFile = new File(globalImageDirPath + catalogId);
-
 
165
		File destinationFile = new File(exportPath);
-
 
166
		copyDirectory(sourceFile, destinationFile, imagePrefix);
-
 
167
 
-
 
168
		/*
-
 
169
		 * Copy the thumbnail and the icon files. This is required so that we can display the
-
 
170
		 * thumbnail on the cart page and icon on the facebook.
-
 
171
		 */
-
 
172
		copyFile(imageDirPath + "thumbnail.jpg", exportPath + File.separator + "thumbnail.jpg");
-
 
173
		copyFile(imageDirPath + "icon.jpg", exportPath + File.separator + "icon.jpg");
-
 
174
		}
-
 
175
 
-
 
176
	/**
-
 
177
	 * Copies the contents of the input file into the output file. Creates the
-
 
178
	 * output file if it doesn't exist already.
-
 
179
	 * 
-
 
180
	 * @param inputFile
-
 
181
	 *            File to be copied.
-
 
182
	 * @param outputFile
-
 
183
	 *            File to be created.
-
 
184
	 * @throws IOException
-
 
185
	 */
-
 
186
	private void copyFile(String inputFile, String outputFile) throws IOException {
-
 
187
		File sourceFile = new File(inputFile);
-
 
188
		File destinationFile = new File(outputFile);
-
 
189
 
-
 
190
		if (!destinationFile.exists())
-
 
191
			destinationFile.createNewFile();
-
 
192
 
-
 
193
		InputStream in = new FileInputStream(sourceFile);
-
 
194
	    OutputStream out = new FileOutputStream(destinationFile);
-
 
195
		// Copy the bits from instream to outstream
-
 
196
		byte[] buf = new byte[1024];
-
 
197
		int len;
-
 
198
		while ((len = in.read(buf)) > 0) {
-
 
199
			out.write(buf, 0, len);
-
 
200
		}
-
 
201
		in.close();
-
 
202
		out.close();
-
 
203
	}
-
 
204
	
-
 
205
 
-
 
206
	/**
-
 
207
	 * Copy the images from one directory to other. It also renames files while copying.
-
 
208
	 * If targetLocation does not exist, it will be created.
-
 
209
	 * @param sourceLocation
-
 
210
	 * @param targetLocation
-
 
211
	 * @param imagePrefix
-
 
212
	 * @throws IOException
-
 
213
	 */
-
 
214
	public void copyDirectory(File sourceLocation , File targetLocation, String imagePrefix) throws IOException {
-
 
215
	 
-
 
216
	    if (sourceLocation.isDirectory()) {
-
 
217
	        if (!targetLocation.exists()) {
-
 
218
	            targetLocation.mkdir();
-
 
219
	        }
-
 
220
	 
-
 
221
	        String[] children = sourceLocation.list();
-
 
222
	        for (int i=0; i<children.length; i++) {
-
 
223
	            copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), imagePrefix);
-
 
224
	        }
-
 
225
	    } else {
-
 
226
	        InputStream in = new FileInputStream(sourceLocation);
-
 
227
	        
-
 
228
        	String fileName = targetLocation.getName().split("\\.")[0];
-
 
229
        	String fileExt = targetLocation.getName().split("\\.")[1];
-
 
230
        	String newFileName = targetLocation.getParent() + File.separator + imagePrefix + "-" + fileName + "-" + this.contentVersion + "." + fileExt; 
-
 
231
 
-
 
232
        	
-
 
233
	        //String fileName = targetLocation
-
 
234
	        OutputStream out = new FileOutputStream(newFileName);
-
 
235
	 
-
 
236
	        // Copy the bits from instream to outstream
-
 
237
	        byte[] buf = new byte[1024];
-
 
238
	        int len;
-
 
239
	        while ((len = in.read(buf)) > 0) {
-
 
240
	            out.write(buf, 0, len);
-
 
241
	        }
-
 
242
	        in.close();
-
 
243
	        out.close();
-
 
244
	    }
-
 
245
	}
-
 
246
	 
-
 
247
	/**
-
 
248
	 * Get the commonly used product properties and store them in a file.  
-
 
249
	 * @param expEntity
-
 
250
	 * @param exportPath
-
 
251
	 */
-
 
252
	private  void getProductPropertiesSnippet(ExpandedEntity expEntity, String exportPath) {
-
 
253
        long catalogId = expEntity.getID();
68
        long catalogId = expEntity.getID();
-
 
69
        String destinationDirectory = Utils.EXPORT_PATH + "documents"
-
 
70
                + File.separator + catalogId;
-
 
71
 
-
 
72
        /*
-
 
73
         * Create the directory for this entity if it didn't exist.
-
 
74
         */
-
 
75
        File destFile = new File(destinationDirectory);
-
 
76
        if (!destFile.exists()) {
-
 
77
            destFile.mkdir();
-
 
78
        }
-
 
79
 
-
 
80
        ExpandedSlide expSlide = expEntity.getExpandedSlide(Utils.AFTER_SALES_SLIDE_DEFINITION_ID);
-
 
81
 
-
 
82
        if (expSlide == null || expSlide.getFreeformContent() == null) {
-
 
83
            return;
-
 
84
        }
-
 
85
 
-
 
86
        List<String> documentLabels = expSlide.getFreeformContent().getDocumentLabels();
-
 
87
        if ((documentLabels == null || documentLabels.isEmpty())) {
-
 
88
            return;
-
 
89
        } else {
-
 
90
            Map<String, Media> medias = expSlide.getFreeformContent().getMedias();
-
 
91
            for (String documentLabel : documentLabels) {
-
 
92
                Media document = medias.get(documentLabel);
-
 
93
                if (document.getCreationTime().getTime() > Long.parseLong(contentVersion)) {
-
 
94
                    copyFile(new File(document.getLocation()), new File(destFile, computeNewFileName(documentPrefix, document.getFileName(),
-
 
95
                            String.valueOf(document.getCreationTime().getTime()))));
-
 
96
                }
-
 
97
            }
-
 
98
        }
-
 
99
    }
-
 
100
 
-
 
101
    /**
-
 
102
     * It Actually copies the images from some given directory to export
-
 
103
     * directory. It also attaches the imagePrefix at the end of image name.
-
 
104
     *
-
 
105
     * @param catalogId
-
 
106
     * @param imagePrefix
-
 
107
     * @throws IOException
-
 
108
     */
-
 
109
    private void generateImages(ExpandedEntity entity, final String imagePrefix)
-
 
110
            throws IOException {
-
 
111
        long catalogId = entity.getID();
-
 
112
        String globalImageDirPath = Utils.CONTENT_DB_PATH + "media"
-
 
113
                + File.separator;
-
 
114
        String globalDefaultImagePath = globalImageDirPath + DEFAULT_JPG;
-
 
115
 
-
 
116
        String imageDirPath = globalImageDirPath + catalogId + File.separator;
-
 
117
        String defaultImagePath = imageDirPath + DEFAULT_JPG;
-
 
118
 
-
 
119
        /*
-
 
120
         * Create the directory for this entity if it didn't exist.
-
 
121
         */
-
 
122
        File f = new File(globalImageDirPath + catalogId);
-
 
123
        if (!f.exists()) {
-
 
124
            f.mkdir();
-
 
125
        }
-
 
126
 
-
 
127
        /*
-
 
128
         * If the default image is not present for this entity, copy the global
-
 
129
         * default image. TODO: This part will be moved to the Jython Script
-
 
130
         */
-
 
131
        File f3 = new File(defaultImagePath);
-
 
132
        if (!f3.exists()) {
-
 
133
            copyFile(new File(globalDefaultImagePath), new File(
-
 
134
                    defaultImagePath));
-
 
135
        }
-
 
136
 
-
 
137
        File staticMediaDirectory = new File(Utils.EXPORT_MEDIA_STATIC_PATH + catalogId);
-
 
138
        if (!staticMediaDirectory.exists()) {
-
 
139
            staticMediaDirectory.mkdir();
-
 
140
        }
-
 
141
 
-
 
142
        File websiteMediaDirectory = new File(Utils.EXPORT_MEDIA_WEBSITE_PATH + catalogId);
-
 
143
        if (!websiteMediaDirectory.exists()) {
-
 
144
            websiteMediaDirectory.mkdir();
-
 
145
        }
-
 
146
 
-
 
147
        /*
-
 
148
         * Copying the generated content from db/media to export/media. This
-
 
149
         * will also insert a creation timestamp tag in the file names.
-
 
150
         */
-
 
151
        for (ExpandedSlide expandedSlide : entity.getExpandedSlides()) {
-
 
152
            FreeformContent freeFormContent = expandedSlide.getFreeformContent();
-
 
153
            if (freeFormContent != null) {
-
 
154
                for (String label : freeFormContent.getImageLabels()) {
-
 
155
                    final Media image = freeFormContent.getMedias().get(label);
-
 
156
                    if (isWebsiteImage(image)) {
-
 
157
                        if (image.getCreationTime().getTime() > Long.valueOf(contentVersion)) {
-
 
158
                            copyFile(new File(image.getLocation()), new File(websiteMediaDirectory, image.getFileName()));
-
 
159
 
-
 
160
                            // In case, default.jpg is changed, icon.jpg and thumbnail.jpg
-
 
161
                            // also need to be updated
-
 
162
                            if (isDefaultImage(image)) {
-
 
163
                                /*
-
 
164
                                 * Copy the thumbnail and the icon files. This is required so that we
-
 
165
                                 * can display the thumbnail on the cart page and icon on the facebook.
-
 
166
                                 */
-
 
167
                                copyFile(new File(imageDirPath + THUMBNAIL_JPG),
-
 
168
                                         new File(websiteMediaDirectory, THUMBNAIL_JPG));
-
 
169
 
-
 
170
                                copyFile(new File(imageDirPath + ICON_JPG),
-
 
171
                                         new File(websiteMediaDirectory, ICON_JPG));
-
 
172
                            }
-
 
173
                        }
-
 
174
                    }
-
 
175
 
-
 
176
                    // Copying all files with timestamps in static directory
-
 
177
                    if (image.getCreationTime().getTime() > Long.valueOf(contentVersion)) {
-
 
178
                        removeFile(staticMediaDirectory, imagePrefix + HYPHON + image.getFileName().split(ESCAPED_DOT)[0]);
-
 
179
 
-
 
180
                        copyFile(new File(image.getLocation()), new File(staticMediaDirectory, computeNewFileName(imagePrefix, image.getFileName(),
-
 
181
                                String.valueOf(image.getCreationTime().getTime()))));
-
 
182
 
-
 
183
                        // If default image is changed icon and thumbnail images are re-copied in static directory
-
 
184
                        if (isDefaultImage(image)) {
-
 
185
                            removeFile(staticMediaDirectory, imagePrefix + HYPHON + THUMBNAIL_JPG.split(ESCAPED_DOT)[0]);
-
 
186
                            removeFile(staticMediaDirectory, imagePrefix + HYPHON + ICON_JPG.split(ESCAPED_DOT)[0]);
-
 
187
 
-
 
188
                            copyFile(new File(imageDirPath + THUMBNAIL_JPG),
-
 
189
                                     new File(staticMediaDirectory, computeNewFileName(imagePrefix, THUMBNAIL_JPG,
-
 
190
                                             String.valueOf(image.getCreationTime().getTime()))));
-
 
191
 
-
 
192
                            copyFile(new File(imageDirPath + ICON_JPG),
-
 
193
                                    new File(staticMediaDirectory, computeNewFileName(imagePrefix, ICON_JPG,
-
 
194
                                            String.valueOf(image.getCreationTime().getTime()))));
-
 
195
                            
-
 
196
                            //FIXME This should be removed once we are ready with changes in ProductListGenerator.
-
 
197
                            copyFile(new File(imageDirPath + ICON_JPG),
-
 
198
                                    new File(staticMediaDirectory, ICON_JPG));
-
 
199
 
-
 
200
                        }
-
 
201
                    }
-
 
202
                }
-
 
203
            }
-
 
204
        }
-
 
205
    }
-
 
206
 
-
 
207
    /**
-
 
208
     * Removes a file in a given directory with a given prefix.
-
 
209
     * It removes only one file.
-
 
210
     *
-
 
211
     * @param staticMediaDirectory  the given directory from where file needs to be removed
-
 
212
     * @param fileNamePrefix    the given prefix of file name that should be removed
-
 
213
     */
-
 
214
    private void removeFile(File staticMediaDirectory, final String fileNamePrefix) {
-
 
215
        // Deleting the file with same name
-
 
216
        File[] fileToBeDeleted = staticMediaDirectory.listFiles(new FilenameFilter() {
-
 
217
            
-
 
218
            @Override
-
 
219
            public boolean accept(File dir, String name) {
-
 
220
                if (name.startsWith(fileNamePrefix)) {
-
 
221
                    return true;
-
 
222
                }
-
 
223
 
-
 
224
                return false;
-
 
225
            }
-
 
226
        });
-
 
227
 
-
 
228
        // Deleting only one file
-
 
229
        if (fileToBeDeleted.length != 0) {
-
 
230
            fileToBeDeleted[0].delete();
-
 
231
        }
-
 
232
    }
-
 
233
 
-
 
234
    /**
-
 
235
     * This method computes new name of a given file. It adds necessary prefix 
-
 
236
     * and suffix to core file name separated by hyphons keeping extension intact.
-
 
237
     * e.g. computeNewFileName("pre", "file.txt", "post") would return "pre-file-post.txt"
-
 
238
     *
-
 
239
     * @param fileNamePrefix    the string to be prefixed
-
 
240
     * @param fileName          the complete name of file
-
 
241
     * @param fileNameSuffix    the string to be suffixed
-
 
242
     * @return the final file name
-
 
243
     */
-
 
244
    private String computeNewFileName(String fileNamePrefix, String fileName, String fileNameSuffix) {
-
 
245
        String name = fileName.split(ESCAPED_DOT)[0];
-
 
246
        String fileExt = fileName.split(ESCAPED_DOT)[1];
-
 
247
        return fileNamePrefix + HYPHON + name + HYPHON + fileNameSuffix + DOT + fileExt;
-
 
248
    }
-
 
249
 
-
 
250
    /**
-
 
251
     * Images to be copied under export/media/website are identified here
-
 
252
     *
-
 
253
     * @param image
-
 
254
     * @return true in case image needs to be copied in website directory
-
 
255
     */
-
 
256
    private boolean isWebsiteImage(Media image) {
-
 
257
        if (isDefaultImage(image)) {
-
 
258
            return true;
-
 
259
        }
-
 
260
 
-
 
261
        return false;
-
 
262
    }
-
 
263
 
-
 
264
    /**
-
 
265
     * Retuens true in case a given image is the default one. False, otherwise.
-
 
266
     */
-
 
267
    private boolean isDefaultImage(Media image) {
-
 
268
        return DEFAULT_JPG.equals(image.getFileName()) || "default".equals(image.getLabel());
-
 
269
    }
-
 
270
 
-
 
271
    /**
-
 
272
     * Copies the contents of the source file into the destination file. Creates
-
 
273
     * the destination file if it doesn't exist already.
-
 
274
     */
-
 
275
    private void copyFile(File sourceFile, File destFile) throws IOException {       
-
 
276
        if (!destFile.exists()) {
-
 
277
            log.info("File: " + destFile.getName());
-
 
278
            log.info("File: " + destFile.getAbsolutePath());
-
 
279
            destFile.createNewFile();
-
 
280
        }
-
 
281
 
-
 
282
        FileChannel source = null;
-
 
283
        FileChannel destination = null;
-
 
284
 
-
 
285
        try {
-
 
286
            source = new FileInputStream(sourceFile).getChannel();
-
 
287
            destination = new FileOutputStream(destFile).getChannel();
-
 
288
            destination.transferFrom(source, 0, source.size());
-
 
289
        } finally {
-
 
290
            if (source != null) {
-
 
291
                source.close();
-
 
292
            }
-
 
293
            if (destination != null) {
-
 
294
                destination.close();
-
 
295
            }
-
 
296
        }
-
 
297
    }
-
 
298
 
-
 
299
    /**
-
 
300
     * Get the commonly used product properties and store them in a file.
-
 
301
     *
-
 
302
     * @param expEntity
-
 
303
     * @param exportPath
-
 
304
     */
-
 
305
    private void getProductPropertiesSnippet(ExpandedEntity expEntity,
-
 
306
            String exportPath) {
-
 
307
        long catalogId = expEntity.getID();
-
 
308
 
254
        try {
309
        try {
255
            expEntity = CreationUtils.getExpandedEntity(catalogId);
310
            expEntity = CreationUtils.getExpandedEntity(catalogId);
256
        } catch (Exception e) {
311
        } catch (Exception e) {
257
            e.printStackTrace();
312
            log.error("Error fetching entity for id: " + catalogId, e);
258
        }
313
        }
259
        
314
 
260
        String metaDescription = "";
315
        String metaDescription = "";
261
        String metaKeywords = "";
316
        String metaKeywords = "";
262
        String entityUrl = EntityUtils.getEntityURL(expEntity);
317
        String entityUrl = EntityUtils.getEntityURL(expEntity);
263
        String title = "";
318
        String title = "";
264
        
319
 
265
        List<Feature>  features = expEntity.getSlide(130054).getFeatures();
320
        List<Feature> features = expEntity.getSlide(130054).getFeatures();
266
        for(Feature feature: features){
321
        for (Feature feature : features) {
267
            if(feature.getFeatureDefinitionID() == 120132){
322
            if (feature.getFeatureDefinitionID() == 120132) {
268
                PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
323
                PrimitiveDataObject dataObject = (PrimitiveDataObject) feature
-
 
324
                        .getBullets().get(0).getDataObject();
269
                title = dataObject.getValue(); 
325
                title = dataObject.getValue();
270
            }
326
            }
271
            if(feature.getFeatureDefinitionID() == 120133){
327
            if (feature.getFeatureDefinitionID() == 120133) {
272
                PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
328
                PrimitiveDataObject dataObject = (PrimitiveDataObject) feature
-
 
329
                        .getBullets().get(0).getDataObject();
273
                metaDescription = dataObject.getValue();
330
                metaDescription = dataObject.getValue();
274
            }
331
            }
275
            if(feature.getFeatureDefinitionID() == 120134){
332
            if (feature.getFeatureDefinitionID() == 120134) {
276
                PrimitiveDataObject dataObject= (PrimitiveDataObject)feature.getBullets().get(0).getDataObject();
333
                PrimitiveDataObject dataObject = (PrimitiveDataObject) feature
-
 
334
                        .getBullets().get(0).getDataObject();
277
                metaKeywords = dataObject.getValue();
335
                metaKeywords = dataObject.getValue();
278
            }
336
            }
279
        }
337
        }
280
 
338
 
281
        try {
339
        try {
282
            JSONObject props = new JSONObject();
340
            JSONObject props = new JSONObject();
283
            Category category = expEntity.getCategory();
341
            Category category = expEntity.getCategory();
284
            String categoryName = category.getLabel();
342
            String categoryName = category.getLabel();
285
            
343
           
286
            props.put("metaDescription", metaDescription);
344
            props.put("metaDescription", metaDescription);
287
            props.put("metaKeywords", metaKeywords);
345
            props.put("metaKeywords", metaKeywords);
288
            props.put("entityUrl", entityUrl);
346
            props.put("entityUrl", entityUrl);
289
            props.put("title", title);
347
            props.put("title", title);
290
            props.put("name", EntityUtils.getProductName(expEntity));
348
            props.put("name", EntityUtils.getProductName(expEntity));
291
            boolean displayAccessories;
349
            boolean displayAccessories;
292
            if(expEntity.getCategory().getParentCategory().getID() != Utils.MOBILE_ACCESSORIES_CATEGORY && expEntity.getCategory().getID() != Utils.LAPTOPS_CATEGORY){
350
            if(expEntity.getCategory().getParentCategory().getID() != Utils.MOBILE_ACCESSORIES_CATEGORY && expEntity.getCategory().getID() != Utils.LAPTOPS_CATEGORY){
293
            	props.put("displayAccessories", "TRUE");
351
                props.put("displayAccessories", "TRUE");
294
            	displayAccessories = true;
352
                displayAccessories = true;
295
    		}else{
353
            }else{
296
    			props.put("displayAccessories", "FALSE" );
354
                props.put("displayAccessories", "FALSE" );
297
    			displayAccessories = false;
355
                displayAccessories = false;
298
    		}   
356
            }  
299
            
357
           
300
            props.put("categoryName", categoryName);
358
            props.put("categoryName", categoryName);
301
            props.put("categoryUrl", categoryName.replaceAll(" ", "-").toLowerCase() + "/" + category.getID());
359
            props.put("categoryUrl", categoryName.replaceAll(SPACE, "-").toLowerCase() + "/" + category.getID());
302
            String categoryUrl = categoryName.replaceAll(" ", "-").toLowerCase() + "/" + category.getID();
360
            String categoryUrl = categoryName.replaceAll(SPACE, "-").toLowerCase() + "/" + category.getID();
303
            
361
           
304
            String brandUrl = expEntity.getBrand().toLowerCase().replace(' ', '-');
362
            String brandUrl = expEntity.getBrand().toLowerCase().replace(' ', '-');
305
            
363
           
306
            String breadCrumb = "<a href='/'>Home</a>&nbsp;&gt;&nbsp;" + 
364
            String breadCrumb = "<a href='/'>Home</a>&nbsp;&gt;&nbsp;" +
307
								"<a href='/" +  categoryUrl + "'>" + categoryName + "</a>&nbsp;&gt;&nbsp;";
365
                                "<a href='/" +  categoryUrl + "'>" + categoryName + "</a>&nbsp;&gt;&nbsp;";
308
            if(displayAccessories){
366
            if(displayAccessories){
309
            	breadCrumb = breadCrumb +  "<a href='/" + brandUrl + "'>" + expEntity.getBrand() + "</a>";
367
                breadCrumb = breadCrumb +  "<a href='/" + brandUrl + "'>" + expEntity.getBrand() + "</a>";
310
            }else{
368
            }else{
311
            	breadCrumb =  breadCrumb + "<a>" + expEntity.getBrand() + "</a>";	
369
                breadCrumb =  breadCrumb + "<a>" + expEntity.getBrand() + "</a>";  
312
            }
370
            }
313
            breadCrumb = breadCrumb +  "&nbsp;<a>" + expEntity.getModelName().trim() + " " + expEntity.getModelNumber().trim() + "</a>";
371
            breadCrumb = breadCrumb +  "&nbsp;<a>" + expEntity.getModelName().trim() + SPACE + expEntity.getModelNumber().trim() + "</a>";
314
            props.put("breadCrumb", breadCrumb);
372
            props.put("breadCrumb", breadCrumb);
315
          
373
         
316
            
374
           
317
            String exportFileName = exportPath + catalogId + File.separator
375
            String exportFileName = exportPath + catalogId + File.separator
318
                    + "ProductPropertiesSnippet.vm";
376
                    + "ProductPropertiesSnippet.vm";
319
            File exportFile = new File(exportFileName);
377
            File exportFile = new File(exportFileName);
320
            if (!exportFile.exists()) {
378
            if (!exportFile.exists()) {
321
                exportFile.createNewFile();
379
                exportFile.createNewFile();
Line 327... Line 385...
327
            writer.write(props.toString());
385
            writer.write(props.toString());
328
 
386
 
329
            writer.flush();
387
            writer.flush();
330
            writer.close();
388
            writer.close();
331
        } catch (Exception e) {
389
        } catch (Exception e) {
332
            e.printStackTrace();
390
            log.error("Error generating JSON", e);
333
        }
391
        }
-
 
392
    }
-
 
393
 
-
 
394
    /**
-
 
395
     * Get slide names and write them in a file. This file will be used in
-
 
396
     * comparison.
-
 
397
     *
-
 
398
     * @param expEntity
-
 
399
     * @param exportPath
-
 
400
     * @throws Exception
-
 
401
     */
-
 
402
    private void getSlidenamesSnippet(ExpandedEntity expEntity,
-
 
403
            String exportPath) throws Exception {
-
 
404
        long catalogId = expEntity.getID();
-
 
405
 
-
 
406
        StringBuilder slideNames = new StringBuilder();
-
 
407
 
-
 
408
        // TODO Investigate why brand + model number is used ?
-
 
409
        slideNames.append(expEntity.getBrand() + SPACE
-
 
410
                + expEntity.getModelNumber() + SPACE + expEntity.getModelName()
-
 
411
                + "\n");
-
 
412
 
-
 
413
        Map<Long, Double> slideScores = CreationUtils
-
 
414
                .getSlideComparisonScores(catalogId);
-
 
415
 
-
 
416
        for (ExpandedSlide expSlide : expEntity.getExpandedSlides()) {
-
 
417
            if (expSlide.getSlideDefinitionID() == Utils.SUMMARY_SLIDE_DEFINITION_ID
-
 
418
                    || expSlide.getSlideDefinitionID() == Utils.AFTER_SALES_SLIDE_DEFINITION_ID) {
-
 
419
                continue;
-
 
420
            }
-
 
421
            slideNames.append(expSlide.getSlideDefinition().getLabel() + "!!!");
-
 
422
 
-
 
423
            String bucketName = "None";
-
 
424
            if (Catalog
-
 
425
                    .getInstance()
-
 
426
                    .getDefinitionsContainer()
-
 
427
                    .getComparisonBucketName(expEntity.getCategoryID(),
-
 
428
                            expSlide.getSlideDefinitionID()) != null) {
-
 
429
                bucketName = Catalog
-
 
430
                        .getInstance()
-
 
431
                        .getDefinitionsContainer()
-
 
432
                        .getComparisonBucketName(expEntity.getCategoryID(),
-
 
433
                                expSlide.getSlideDefinitionID());
-
 
434
            }
-
 
435
            slideNames.append(bucketName + "!!!");
334
	}
436
 
-
 
437
            double score = 0;
-
 
438
            if (slideScores.get(expSlide.getSlideDefinitionID()) != null) {
-
 
439
                score = slideScores.get(expSlide.getSlideDefinitionID());
-
 
440
            }
335
 
441
 
336
	/**
-
 
337
	 * Get slide names and write them in a file. This file will be used in comparison.
-
 
338
	 * @param expEntity
-
 
339
	 * @param exportPath
-
 
340
	 * @throws Exception
-
 
341
	 */
-
 
342
    private void getSlidenamesSnippet(ExpandedEntity expEntity, String exportPath) throws Exception{
-
 
343
	    long catalogId = expEntity.getID();
-
 
344
        
-
 
345
	    StringBuilder slideNames = new StringBuilder();
-
 
346
	    //TODO Investigate why brand + model number is used ?
-
 
347
	    slideNames.append(expEntity.getBrand() + " " + expEntity.getModelNumber() + " " + expEntity.getModelName() + "\n");
-
 
348
	    
-
 
349
	    Map<Long, Double> slideScores = CreationUtils.getSlideComparisonScores(catalogId);
-
 
350
	    
-
 
351
	    for(ExpandedSlide expSlide: expEntity.getExpandedSlides()){
-
 
352
	        if(expSlide.getSlideDefinitionID() == Utils.SUMMARY_SLIDE_DEFINITION_ID || expSlide.getSlideDefinitionID() == Utils.AFTER_SALES_SLIDE_DEFINITION_ID ){
-
 
353
	            continue;
-
 
354
	        }
-
 
355
	        slideNames.append(expSlide.getSlideDefinition().getLabel() + "!!!");
-
 
356
	        
-
 
357
	        String bucketName = "None";
-
 
358
	        if(Catalog.getInstance().getDefinitionsContainer().getComparisonBucketName(expEntity.getCategoryID(), expSlide.getSlideDefinitionID()) != null){
-
 
359
	            bucketName = Catalog.getInstance().getDefinitionsContainer().getComparisonBucketName(expEntity.getCategoryID(), expSlide.getSlideDefinitionID());
-
 
360
	        }
-
 
361
	        slideNames.append(bucketName + "!!!");
-
 
362
	        
-
 
363
	        double score = 0;
-
 
364
	        if(slideScores.get(expSlide.getSlideDefinitionID())!=null){
-
 
365
	            score = slideScores.get(expSlide.getSlideDefinitionID());
-
 
366
	        }
-
 
367
	
-
 
368
	        DecimalFormat oneDForm = new DecimalFormat("#.#");
442
            DecimalFormat oneDForm = new DecimalFormat("#.#");
369
	        score = Double.valueOf(oneDForm.format(score));
443
            score = Double.valueOf(oneDForm.format(score));
370
	
444
 
371
	        slideNames.append(score + "\n");
445
            slideNames.append(score + "\n");
372
	    }
446
        }
373
 
447
 
374
        String exportFileName = exportPath + catalogId + File.separator + "SlideNamesSnippet.vm";
448
        String exportFileName = exportPath + catalogId + File.separator
-
 
449
                + "SlideNamesSnippet.vm";
375
        File exportFile = new File(exportFileName);
450
        File exportFile = new File(exportFileName);
376
        if(!exportFile.exists()) {
451
        if (!exportFile.exists()) {
377
            exportFile.createNewFile();
452
            exportFile.createNewFile();
378
        }
453
        }
379
        
454
 
380
        BufferedWriter writer = new BufferedWriter(
455
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
381
            new OutputStreamWriter(new FileOutputStream(exportFile)));
456
                new FileOutputStream(exportFile)));
382
 
457
 
383
        writer.write(slideNames.toString());
458
        writer.write(slideNames.toString());
384
        writer.flush();
459
        writer.flush();
385
        writer.close();
460
        writer.close();
386
	    
-
 
387
	}
-
 
388
 
461
 
389
    
462
    }
-
 
463
 
390
	/**
464
    /**
391
	 * Get related accessories
465
     * Get related accessories
-
 
466
     *
392
	 * @param expEntity
467
     * @param expEntity
393
	 * @param exportPath
468
     * @param exportPath
394
	 * @throws Exception
469
     * @throws Exception
395
	 */
470
     */
396
    private void getRelatedAccessories(ExpandedEntity expEntity, String exportPath) throws Exception{
471
    private void getRelatedAccessories(ExpandedEntity expEntity,
-
 
472
            String exportPath) throws Exception {
397
	    long catalogId = expEntity.getID();
473
        long catalogId = expEntity.getID();
398
        
474
 
399
	    Map<Long, List<Long>> relatedAccessories = CreationUtils.getRelatedAccessories().get(catalogId);
475
        Map<Long, List<Long>> relatedAccessories = CreationUtils
-
 
476
                .getRelatedAccessories().get(catalogId);
400
	    List<Long> priorityList = new ArrayList<Long>();
477
        List<Long> priorityList = new ArrayList<Long>();
401
	    int individualLimit = 2;
478
        int individualLimit = 2;
402
	    int totalLimit = 10;
479
        int totalLimit = 10;
403
	    priorityList.add(Utils.CARRYING_CASE);
480
        priorityList.add(Utils.CARRYING_CASE);
404
	    priorityList.add(Utils.SCREEN_GUARD);
481
        priorityList.add(Utils.SCREEN_GUARD);
405
	    priorityList.add(Utils.BATTERY);
482
        priorityList.add(Utils.BATTERY);
406
	    priorityList.add(Utils.MEMORY_CARD);
483
        priorityList.add(Utils.MEMORY_CARD);
407
	    priorityList.add(Utils.BLUETOOTH_HEADSET);
484
        priorityList.add(Utils.BLUETOOTH_HEADSET);
408
	    priorityList.add(Utils.HEADSET);
485
        priorityList.add(Utils.HEADSET);
409
	    priorityList.add(Utils.CHARGER);
486
        priorityList.add(Utils.CHARGER);
410
	    
487
 
411
	    StringBuffer sb = new StringBuffer();
488
        StringBuffer sb = new StringBuffer();
412
	    int totalCount = 0;
489
        int totalCount = 0;
413
	    if(relatedAccessories!=null){
490
        if (relatedAccessories != null) {
414
		    for(Long catID: priorityList){
491
            for (Long catID : priorityList) {
415
		    	int individualCount = 0;
492
                int individualCount = 0;
416
		    	List<Long> ents = relatedAccessories.get(catID);
493
                List<Long> ents = relatedAccessories.get(catID);
417
		    	if(ents != null && !ents.isEmpty()){
494
                if (ents != null && !ents.isEmpty()) {
418
		    		if(ents.size()>individualLimit){
495
                    if (ents.size() > individualLimit) {
419
		    			ents = ents.subList(0, individualLimit);
496
                        ents = ents.subList(0, individualLimit);
420
		    		}
497
                    }
421
		    		for(Long entID: ents){
498
                    for (Long entID : ents) {
422
		    			if(totalLimit > totalCount){
499
                        if (totalLimit > totalCount) {
423
		    				sb.append(entID + "\n");
500
                            sb.append(entID + "\n");
424
		    				individualCount++;
501
                            individualCount++;
425
		    				totalCount++;
502
                            totalCount++;
426
		    			}
503
                        }
427
		    		}
504
                    }
428
		    	}
505
                }
429
		    }
506
            }
430
	    }
507
        }
431
	    
508
 
432
        String exportFileName = exportPath + catalogId + File.separator + "RelatedAccessories.vm";
509
        String exportFileName = exportPath + catalogId + File.separator
-
 
510
                + "RelatedAccessories.vm";
433
        File exportFile = new File(exportFileName);
511
        File exportFile = new File(exportFileName);
434
        if(!exportFile.exists()) {
512
        if (!exportFile.exists()) {
435
            exportFile.createNewFile();
513
            exportFile.createNewFile();
436
        }
514
        }
437
        
515
 
438
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportFile)));
516
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
-
 
517
                new FileOutputStream(exportFile)));
439
 
518
 
440
        writer.write(sb.toString());
519
        writer.write(sb.toString());
441
        writer.flush();
520
        writer.flush();
442
        writer.close();
521
        writer.close();
443
	    
-
 
444
	}
-
 
445
 
522
 
446
    
523
    }
-
 
524
 
447
    /**
525
    /**
448
	 * Get most compared phones
526
     * Get most compared phones
-
 
527
     *
449
	 * @param expEntity
528
     * @param expEntity
450
	 * @param exportPath
529
     * @param exportPath
451
	 * @throws Exception
530
     * @throws Exception
452
	 */
531
     */
453
    private void getMostComparedProducts(ExpandedEntity expEntity, String exportPath) throws Exception{
532
    private void getMostComparedProducts(ExpandedEntity expEntity,
-
 
533
            String exportPath) throws Exception {
454
	    long catalogId = expEntity.getID();
534
        long catalogId = expEntity.getID();
455
        
535
 
456
	    Map<Long, Long> comparedPhones = CreationUtils.getComparisonStats().get(catalogId);
536
        Map<Long, Long> comparedPhones = CreationUtils.getComparisonStats()
-
 
537
                .get(catalogId);
457
	    
538
 
458
	    StringBuffer sb = new StringBuffer();
539
        StringBuffer sb = new StringBuffer();
459
	    int maxCount = 10;
540
        int maxCount = 10;
460
	    int count = 0;
541
        int count = 0;
461
	    if(comparedPhones != null){
542
        if (comparedPhones != null) {
462
		    for(Long entityID: comparedPhones.keySet()){
543
            for (Long entityID : comparedPhones.keySet()) {
463
		    	if(count > maxCount){
544
                if (count > maxCount) {
464
					break;
545
                    break;
465
				}
546
                }
466
				sb.append(entityID + "\n");
547
                sb.append(entityID + "\n");
467
				count++;
548
                count++;
468
		    }
549
            }
469
	    }
550
        }
470
	    
551
 
471
        String exportFileName = exportPath + catalogId + File.separator + "MostComparedProducts.vm";
552
        String exportFileName = exportPath + catalogId + File.separator
-
 
553
                + "MostComparedProducts.vm";
472
        File exportFile = new File(exportFileName);
554
        File exportFile = new File(exportFileName);
473
        if(!exportFile.exists()) {
555
        if (!exportFile.exists()) {
474
            exportFile.createNewFile();
556
            exportFile.createNewFile();
475
        }
557
        }
476
        
558
 
477
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportFile)));
559
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
-
 
560
                new FileOutputStream(exportFile)));
478
 
561
 
479
        writer.write(sb.toString());
562
        writer.write(sb.toString());
480
        writer.flush();
563
        writer.flush();
481
        writer.close();
564
        writer.close();
482
	    
565
    }
483
	}
-
 
484
 
-
 
485
	
-
 
486
 
566
 
487
	/**
567
    /**
488
	 * Get the required parameters for generating velocity content.
568
     * Get the required parameters for generating velocity content.
-
 
569
     *
489
	 * @param expEntity
570
     * @param expEntity
490
	 * @return
571
     * @return
491
	 * @throws Exception
572
     * @throws Exception
492
	 */
573
     */
493
	private Map<String, String> getEntityParameters(ExpandedEntity expEntity) throws Exception{
574
    private Map<String, String> getEntityParameters(ExpandedEntity expEntity)
-
 
575
            throws Exception {
494
        Map<String, String> params = new HashMap<String, String>();
576
        Map<String, String> params = new HashMap<String, String>();
495
        String title = EntityUtils.getProductName(expEntity);
577
        String title = EntityUtils.getProductName(expEntity);
496
        String brandName = expEntity.getBrand().trim();
578
        String brandName = expEntity.getBrand().trim();
497
        String productName = ((expEntity.getModelName() != null) ? expEntity
579
        String productName = ((expEntity.getModelName() != null) ? expEntity
498
                .getModelName().trim() + SPACE : "")
580
                .getModelName().trim() + SPACE : "")
Line 600... Line 682...
600
        }
682
        }
601
        params.put("CATALOG_ID", expEntity.getID() + "");
683
        params.put("CATALOG_ID", expEntity.getID() + "");
602
        params.put("TAGLINE", tagline);
684
        params.put("TAGLINE", tagline);
603
        params.put("WARRANTY", warranty);
685
        params.put("WARRANTY", warranty);
604
        params.put("TINY_SNIPPET", tinySnippet);
686
        params.put("TINY_SNIPPET", tinySnippet);
605
        params.put("IMAGE_PREFIX", EntityUtils.getImagePrefix(expEntity));
687
        params.put("IMAGE_PREFIX", EntityUtils.getMediaPrefix(expEntity));
606
        params.put("contentVersion", contentVersion);
688
        params.put("contentVersion", contentVersion);
-
 
689
        params.put("skinImageCreationTime", String.valueOf(EntityUtils.getCreationTimeFromSummarySlide(expEntity, "skin")));
-
 
690
        params.put("DEFAULT_IMAGE_SUFFIX", String.valueOf(EntityUtils.getCreationTimeFromSummarySlide(expEntity, "default")));
607
 
691
 
608
        return params;
692
        return params;
609
    }
693
    }
610
	
694
   
611
 
695
 
612
	/**
696
    /**
613
	 * Generates content for the specified entity embedding links to the
697
     * Generates content for the specified entity embedding links to the
614
	 * specified domain name.
698
     * specified domain name.
615
	 * 
699
     *
616
	 * The method updates the member variable problems in any of the following
700
     * The method updates the member variable problems in any of the following
617
	 * four cases:
701
     * four cases:
618
	 * <ol>
702
     * <ol>
619
	 * <li>The entity is not ready.
703
     * <li>The entity is not ready.
620
	 * <li>The category has not been updated yet. (Set to -1).
704
     * <li>The category has not been updated yet. (Set to -1).
621
	 * <li>There are no items in the catalog corresponding to this entity.
705
     * <li>There are no items in the catalog corresponding to this entity.
622
	 * <li>There are no active or content-complete items in the catalog
706
     * <li>There are no active or content-complete items in the catalog
623
	 * corresponding to this entity.
707
     * corresponding to this entity.
624
	 * <li>Neither the items have been updated nor the content has been updated.
708
     * <li>Neither the items have been updated nor the content has been updated.
625
	 * </ol>
709
     * </ol>
626
	 * 
710
     *
627
	 * @param entity
711
     * @param entity
628
	 *            - Entity for which the content has to be generated.
712
     *            - Entity for which the content has to be generated.
629
	 * @param domain
713
     * @param domain
630
	 *            - The domain name to be used to serve static content.
714
     *            - The domain name to be used to serve static content.
631
	 * @param exportPath
715
     * @param exportPath
632
	 *            - Local file system path where content has to be generated.
716
     *            - Local file system path where content has to be generated.
633
	 * @return -True if content is generated successfully, False otherwise.
-
 
634
	 * @throws Exception
717
     * @throws Exception
635
	 */
718
     */
636
	public void generateContentForOneEntity(Entity entity, String exportPath) throws Exception{
719
    public void generateContentForOneEntity(Entity entity, String exportPath)
637
		String mediaPath = Utils.EXPORT_MEDIA_PATH + entity.getID(); 
720
            throws Exception {
638
		deleteOldResources(mediaPath, exportPath + entity.getID()); //Remove old resources. ie images and html content
-
 
639
        ExpandedEntity expEntity = new ExpandedEntity(entity);
721
        ExpandedEntity expEntity = new ExpandedEntity(entity);
640
		long catalogId = expEntity.getID();
722
        long catalogId = expEntity.getID();
641
		
723
 
642
		//Create new directory
724
        // Create new directory
643
		File exportDir = new File(exportPath + catalogId);
725
        File exportDir = new File(exportPath + catalogId);
644
		if(!exportDir.exists()) {
726
        if (!exportDir.exists()) {
645
			exportDir.mkdir();
727
            exportDir.mkdir();
646
		}
728
        }
647
		
729
 
648
		VelocityContext context = new VelocityContext();
730
        VelocityContext context = new VelocityContext();
649
		
731
 
650
		context.put("imagePrefix", EntityUtils.getImagePrefix(expEntity));
732
        String mediaPrefix = EntityUtils.getMediaPrefix(expEntity);
-
 
733
        context.put("mediaPrefix", mediaPrefix);
651
		context.put("expentity", expEntity);
734
        context.put("expentity", expEntity);
652
		context.put("contentVersion", this.contentVersion);
735
        context.put("contentVersion", this.contentVersion);
653
		context.put("defs", Catalog.getInstance().getDefinitionsContainer());
736
        context.put("defs", Catalog.getInstance().getDefinitionsContainer());
654
        context.put("helpdocs", CreationUtils.getHelpdocs());
737
        context.put("helpdocs", CreationUtils.getHelpdocs());
655
        context.put("params", getEntityParameters(expEntity));
738
        context.put("params", getEntityParameters(expEntity));
656
        
739
 
657
		List<String> filenames = new ArrayList<String>();
740
        List<String> filenames = new ArrayList<String>();
658
		filenames.add("ProductDetail");
741
        filenames.add("ProductDetail");
659
		filenames.add("WidgetSnippet");
742
        filenames.add("WidgetSnippet");
660
		filenames.add("HomeSnippet");
743
        filenames.add("HomeSnippet");
661
		filenames.add("SearchSnippet");
744
        filenames.add("SearchSnippet");
662
		filenames.add("CategorySnippet");
745
        filenames.add("CategorySnippet");
663
		filenames.add("SlideGuide");
746
        filenames.add("SlideGuide");
664
		filenames.add("MyResearchSnippet");
747
        filenames.add("MyResearchSnippet");
665
		filenames.add("AfterSales");
748
        filenames.add("AfterSales");
666
		if(expEntity.getCategory().getParentCategory().getID() != Utils.MOBILE_ACCESSORIES_CATEGORY && expEntity.getCategory().getID() != Utils.LAPTOPS_CATEGORY){
749
        if (expEntity.getCategory().getParentCategory().getID() != Utils.MOBILE_ACCESSORIES_CATEGORY
-
 
750
                && expEntity.getCategory().getID() != Utils.LAPTOPS_CATEGORY) {
667
			filenames.add("PhonesIOwnSnippet");
751
            filenames.add("PhonesIOwnSnippet");
668
			filenames.add("CompareProductSnippet");
752
            filenames.add("CompareProductSnippet");
669
			filenames.add("ComparisonSnippet");
753
            filenames.add("ComparisonSnippet");
670
			filenames.add("CompareProductSummarySnippet");
754
            filenames.add("CompareProductSummarySnippet");
671
			// This method wont use any velocity file, So calling directly
755
            // This method wont use any velocity file, So calling directly
672
			getSlidenamesSnippet(expEntity, exportPath);
756
            getSlidenamesSnippet(expEntity, exportPath);
673
			getRelatedAccessories(expEntity, exportPath);
757
            getRelatedAccessories(expEntity, exportPath);
674
			getMostComparedProducts(expEntity, exportPath);
758
            getMostComparedProducts(expEntity, exportPath);
675
		}
759
        }
676
		
-
 
677
		
760
 
678
		// This method wont use any velocity file, So calling directly
761
        // This method wont use any velocity file, So calling directly
679
		getProductPropertiesSnippet(expEntity, exportPath);
762
        getProductPropertiesSnippet(expEntity, exportPath);
680
		
763
 
681
		applyVelocityTemplate(filenames,exportPath,context,catalogId);
764
        applyVelocityTemplate(filenames, exportPath, context, catalogId);
682
		
765
 
683
		generateImages(expEntity.getID(), EntityUtils.getImagePrefix(expEntity));
766
        generateImages(expEntity, mediaPrefix);
684
		
767
 
685
		copyDocuments(expEntity);
768
        copyDocuments(expEntity, mediaPrefix);
686
 
-
 
687
	}
769
    }
688
	
770
 
689
	/**
771
    /**
690
	 * Get list of files and apply velocity templates on them
772
     * Get list of files and apply velocity templates on them
-
 
773
     *
691
	 * @param filenames
774
     * @param filenames
692
	 * @param exportPath
775
     * @param exportPath
693
	 * @param context
776
     * @param context
694
	 * @param catalogId
777
     * @param catalogId
695
	 */
778
     */
-
 
779
    private void applyVelocityTemplate(List<String> filenames,
696
	private void applyVelocityTemplate(List<String> filenames, String exportPath, VelocityContext context, long catalogId){
780
            String exportPath, VelocityContext context, long catalogId) {
697
		try {
781
        try {
698
			Properties p = new Properties();
782
            Properties p = new Properties();
699
			p.setProperty("resource.loader", "file");
783
            p.setProperty("resource.loader", "file");
-
 
784
            p.setProperty("file.resource.loader.class",
700
			p.setProperty("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.FileResourceLoader");
785
                    "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
701
			p.setProperty( "file.resource.loader.path", Utils.VTL_SRC_PATH);
786
            p.setProperty("file.resource.loader.path", Utils.VTL_SRC_PATH);
702
			Velocity.init(p);
787
            Velocity.init(p);
703
			for(String filename: filenames){
788
            for (String filename : filenames) {
704
				Template template = Velocity.getTemplate(filename + ".vm");
789
                Template template = Velocity.getTemplate(filename + ".vm");
-
 
790
                BufferedWriter writer = new BufferedWriter(
-
 
791
                        new OutputStreamWriter(
705
				BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + catalogId + File.separator +filename+".vm")));
792
                                new FileOutputStream(exportPath + catalogId
-
 
793
                                        + File.separator + filename + ".vm")));
706
				template.merge(context, writer);
794
                template.merge(context, writer);
707
				writer.flush();
795
                writer.flush();
708
				writer.close();	
796
                writer.close();
709
			}
797
            }
710
		}catch (ResourceNotFoundException e) {
798
        } catch (ResourceNotFoundException e) {
711
			// TODO Auto-generated catch block
799
            log.error("Error generating velocity templates", e);
712
			e.printStackTrace();
-
 
713
		} catch (IOException e) {
800
        } catch (IOException e) {
714
			// TODO Auto-generated catch block
801
            log.error("Error generating velocity templates", e);
715
			e.printStackTrace();
-
 
716
		} catch (ParseErrorException e) {
802
        } catch (ParseErrorException e) {
717
			// TODO Auto-generated catch block
803
            log.error("Error generating velocity templates", e);
718
			e.printStackTrace();
-
 
719
		} catch (Exception e) {
804
        } catch (Exception e) {
720
			// TODO Auto-generated catch block
805
            log.error("Error generating velocity templates", e);
721
			e.printStackTrace();
-
 
722
		}
806
        }
723
	}	
807
    }
724
}
808
}
725
809