Subversion Repositories SmartDukaan

Rev

Rev 2362 | Rev 2369 | 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.util;
2367 rajveer 2
import java.io.File;
3
import java.io.IOException;
2171 rajveer 4
import java.util.ArrayList;
5
import java.util.Date;
2367 rajveer 6
import java.util.HashMap;
2171 rajveer 7
import java.util.LinkedHashMap;
8
import java.util.List;
9
import java.util.Map;
10
 
11
import in.shop2020.metamodel.core.Entity;
12
import in.shop2020.metamodel.core.EntityState;
13
import in.shop2020.metamodel.core.EntityStatus;
14
import in.shop2020.metamodel.util.CreationUtils;
15
import in.shop2020.metamodel.util.ExpandedEntity;
16
import in.shop2020.model.v1.catalog.InventoryService.Client;
17
import in.shop2020.model.v1.catalog.Item;
18
import in.shop2020.model.v1.catalog.status;
19
import in.shop2020.thrift.clients.CatalogServiceClient;
2367 rajveer 20
import in.shop2020.ui.util.PriceInsertor;
2171 rajveer 21
import in.shop2020.ui.util.NewVUI;
22
 
23
import org.apache.commons.cli.*;
24
 
25
 
26
 
27
public class ContentGenerationUtility {
28
    private static Options options = null; // Command line options
29
 
2367 rajveer 30
    private static final String UPDATE_TYPE_OPTION = "u";
2171 rajveer 31
    private static final String GENERATION_TYPE_OPTION = "t";
32
    private static final String ENTITY_ID_OPTION = "e";
33
 
2367 rajveer 34
    private static String UPDATE_TYPE = "CONTENT";
2171 rajveer 35
    private static String GENERATION_TYPE = "INCREMENTAL";
36
    private static String ENTITY_ID = "ALL";
37
    Map<Long, Entity> entities;
38
    List<Item> items;
2367 rajveer 39
    List<Item> contentCompleteItems  = new ArrayList<Item>();
40
    List<Item> phasedOutItems;
2171 rajveer 41
    CatalogServiceClient csc;
42
    Client client;
43
    Map<Long, List<Item>> entityIdItemMap = new LinkedHashMap<Long, List<Item>>();
44
    private CommandLine cmd = null; // Command Line arguments
45
    Long lastGenerationTime;
46
 
47
    static{
48
        options = new Options();
49
        options.addOption(GENERATION_TYPE_OPTION, true, "Generation type");
2367 rajveer 50
        options.addOption(UPDATE_TYPE_OPTION, true, "Default is : " + UPDATE_TYPE);
2171 rajveer 51
        options.addOption(ENTITY_ID_OPTION, true, "all entities " + ENTITY_ID + " by default");
52
    }
53
 
54
    public ContentGenerationUtility() throws Exception{
55
        csc = new CatalogServiceClient();
56
        client = csc.getClient();
57
    }
58
 
2367 rajveer 59
 
2171 rajveer 60
    /**
61
     * @param args
62
     * @throws Exception 
63
     */
64
    public static void main(String[] args) throws Exception {
65
        ContentGenerationUtility cgu = new ContentGenerationUtility();
2367 rajveer 66
        //Load arguments
2171 rajveer 67
        cgu.loadArgs(args);
2367 rajveer 68
        //Call method based on arguments
69
        cgu.callMethod();
2171 rajveer 70
    }
2367 rajveer 71
 
2171 rajveer 72
 
2367 rajveer 73
	/**
2171 rajveer 74
     * Validate and set command line arguments.
75
     * Exit after printing usage if anything is astray
76
     * @param args String[] args as featured in public static void main()
77
     */
78
    private void loadArgs(String[] args){
79
        CommandLineParser parser = new PosixParser();
80
        try {
81
            cmd = parser.parse(options, args);
82
        } catch (ParseException e) {
83
            System.err.println("Error parsing arguments");
84
            e.printStackTrace();
85
            System.exit(1);
86
        }
87
 
88
        // Check for mandatory args
89
 
2367 rajveer 90
        if (!( cmd.hasOption(GENERATION_TYPE_OPTION)  &&  cmd.hasOption(UPDATE_TYPE_OPTION))){
2171 rajveer 91
            HelpFormatter formatter = new HelpFormatter();
2367 rajveer 92
            formatter.printHelp("java ContentGenerationUtility.class -t { ALL | INCREMENTAL | ONE } -u { CONTENT | CATALOG } -e {EntityId} ", options);
2171 rajveer 93
            System.exit(1);
94
        }
95
 
96
        GENERATION_TYPE = cmd.getOptionValue(GENERATION_TYPE_OPTION);
2367 rajveer 97
 
98
        UPDATE_TYPE = cmd.getOptionValue(UPDATE_TYPE_OPTION);
99
 
2171 rajveer 100
        // Look for optional args.
101
        if(GENERATION_TYPE.equals("ONE")){
102
            if (cmd.hasOption(ENTITY_ID_OPTION)){
103
                ENTITY_ID = cmd.getOptionValue(ENTITY_ID_OPTION);
104
            }else{
105
                HelpFormatter formatter = new HelpFormatter();
2367 rajveer 106
                formatter.printHelp("java ContentGenerationUtility.class -t { ALL | INCREMENTAL | ONE } -u { CONTENT | CATALOG } -e {EntityId} ", options);
2171 rajveer 107
                System.exit(1);
108
            }
109
        }
2367 rajveer 110
    }
111
 
112
    /**
113
     * Call method based on arguments
114
     * @throws Exception
115
     */
116
    private void callMethod() throws Exception{
117
    	if(UPDATE_TYPE.equals("CONTENT")){
118
    		this.generateContent();	
119
    	}
120
 
121
    	if(UPDATE_TYPE.equals("CATALOG")){
122
    		this.updatePrices();
123
    	}	
124
    }
125
 
126
 
127
 
128
	public boolean deleteDir(File dir) {
129
	    if (dir.isDirectory()) {
130
	        String[] children = dir.list();
131
	        for (int i=0; i<children.length; i++) {
132
	            boolean success = deleteDir(new File(dir, children[i]));
133
	            if (!success) {
134
	                return false;
135
	            }
136
	        }
137
	    }
138
	    // The directory is now empty so delete it
139
	    return dir.delete();
140
	}
141
 
142
 
143
	private void removeOldResources() throws IOException{
144
		File f = new File(Utils.EXPORT_SOLR_PATH);
145
		if(f.exists()){
146
			deleteDir(f);
147
		}
148
		f.createNewFile();
149
		f.mkdir();
150
 
151
		File f1 = new File(Utils.EXPORT_ENTITIES_PATH_LOCALHOST);
152
		if(f1.exists()){
153
			deleteDir(f1);
154
		}
155
		f1.createNewFile();
156
		f1.mkdir();
157
 
158
		File f2 = new File(Utils.EXPORT_ENTITIES_PATH_SAHOLIC);
159
		if(f2.exists()){
160
			deleteDir(f2);
161
		}
162
		f2.createNewFile();
163
		f2.mkdir();
164
 
165
		File f3 = new File(Utils.EXPORT_ENTITIES_PATH_SHOP2020);
166
		if(f3.exists()){
167
			deleteDir(f3);
168
		}
169
		f3.createNewFile();
170
		f3.mkdir();
171
	}
172
 
173
    /**
174
     * Update the prices in the generated content
175
     * @throws Exception
176
     */
177
    private void updatePrices() throws Exception {
178
    	lastGenerationTime = new Long(0);
179
        if(GENERATION_TYPE.equals("ONE")) {
180
            items = client.getItemsByCatalogId(Long.parseLong(ENTITY_ID));
181
        }else{
182
            items = client.getAllItemsByStatus(status.ACTIVE);
183
            items.addAll(client.getAllItemsByStatus(status.PAUSED));
184
            items.addAll(client.getAllItemsByStatus(status.CONTENT_COMPLETE));
185
 
186
            //Clean up the data from the solr directories.
187
            removeOldResources();
188
 
189
        }
190
        //this still needs to be evolved. Must not be used.
191
        if(GENERATION_TYPE.equals("INCREMENTAL")) {
192
        }
193
 
194
 
2171 rajveer 195
 
2367 rajveer 196
        //Populate the entityIdIemMap 
197
        populateEntityIdItemMap();
198
 
199
        PriceInsertor priceInserter = new PriceInsertor();
200
 
201
        for(Map.Entry<Long, List<Item>> entry: entityIdItemMap.entrySet()){
202
        	long entityId = entry.getKey();
203
        	List<Item> items = entry.getValue();
204
            //TODO Domain name and destination  directory should be read from properties file
205
        	priceInserter.insertPriceInHtml(items, entityId, "saholic.com", Utils.EXPORT_ENTITIES_PATH_SAHOLIC);
206
        	priceInserter.insertPriceInHtml(items, entityId, "shop2020.in", Utils.EXPORT_ENTITIES_PATH_SHOP2020);
207
        	priceInserter.insertPriceInHtml(items, entityId, "localhost:8090", Utils.EXPORT_ENTITIES_PATH_LOCALHOST);
208
        	priceInserter.insertPriceInSolrData(entityId, getMinPrice(items));
209
            // Mark content-complete items as active after the content has been generated
210
        	for(Item item: items){
211
        		if(item.getItemStatus()==status.CONTENT_COMPLETE){
212
                    item.setItemStatus(status.ACTIVE);
213
                    item.setStatus_description("This item is active");
214
                    client.updateItem(item);
215
        		}
216
        	}
217
        }
218
 
219
        //Generate partners and json objects for phones only
220
        if(!GENERATION_TYPE.equals("ONE")) {
221
        	ProductListGenerator generator = new ProductListGenerator(entityIdItemMap);
222
			generator.generateProductsListXML();
223
			generator.generateProductListJavascript();
224
        }
225
 
2171 rajveer 226
    }
227
 
2367 rajveer 228
 
2171 rajveer 229
    /**
2367 rajveer 230
     * 
231
     * @param items
232
     * @return the minimum price of the items
233
     */
234
	private double getMinPrice(List<Item> items){
235
        double minPrice = Double.MAX_VALUE;
236
        for(Item item: items){
237
            if(minPrice > item.getSellingPrice()){
238
                minPrice = item.getSellingPrice();
239
            }
240
        }
241
        return minPrice;
242
    }
243
 
244
 
245
	/**
2171 rajveer 246
     * Generates content for the specified entity embedding links to the
247
     * specified domain name.
248
     * 
2367 rajveer 249
     * The method will not generate content if one of the following conditions is met:
2171 rajveer 250
     * <ol>
251
     * <li>The entity is not ready.
252
     * <li>The category has not been updated yet. (Set to -1).
2367 rajveer 253
     * <li>The content has not been updated.
2171 rajveer 254
     * </ol>
2367 rajveer 255
     *
256
     * @throws
2171 rajveer 257
     */
258
    private void generateContent() throws Exception{
2367 rajveer 259
        if(GENERATION_TYPE.equals("ALL")) {
260
        	entities = CreationUtils.getEntities();
261
            lastGenerationTime = new Long(0);
262
        }else if(GENERATION_TYPE.equals("ONE")) {
263
        	entities = new HashMap<Long, Entity>();
264
        	entities.put(Long.parseLong(ENTITY_ID), CreationUtils.getEntity(Long.parseLong(ENTITY_ID)));
2171 rajveer 265
            lastGenerationTime = new Long(0);   
266
        }else{
2367 rajveer 267
        	entities = CreationUtils.getEntities();
2171 rajveer 268
            lastGenerationTime = CreationUtils.getLastContentGenerationTime();
269
            if(lastGenerationTime==null){
270
                lastGenerationTime = new Long(0);
271
            }    
272
        }
2367 rajveer 273
        //Filter invalid entities here
274
        List<Entity> validEntities = new ArrayList<Entity>();
275
        for(long entityID: entities.keySet()){
276
        	if(isValidEntity(entities.get(entityID))){
277
        		validEntities.add(entities.get(entityID));
278
        	}
2171 rajveer 279
        }
2367 rajveer 280
        //Calculate comparison scores
281
        NewCMP cmp = new NewCMP(validEntities);
2171 rajveer 282
        Map<Long, Map<Long, Double>> slideScoresByEntity = cmp.getSlideScores();
2367 rajveer 283
        CreationUtils.storeSlideScores(slideScoresByEntity);
2171 rajveer 284
 
285
        NewVUI vui = new NewVUI(lastGenerationTime);
2367 rajveer 286
        for(Entity entity: validEntities){
287
        		vui.generateHtmlForOneEntity(entity, Utils.EXPORT_VELOCITY_PATH);
2171 rajveer 288
        }
2367 rajveer 289
        CreationUtils.storeLastContentGenerationTime((new Date()).getTime());
290
 
291
 
292
        NewIR ir = new NewIR(validEntities);
2227 rajveer 293
        ir.exportIRData();
2367 rajveer 294
        //ir.transformIrDataXMLtoSolrXML();
2227 rajveer 295
        ir.exportIRMetaData();
296
        ir.transformIrMetaDataXMLSolrSchemaXML();
297
 
2171 rajveer 298
    }
2367 rajveer 299
 
2171 rajveer 300
 
301
    /**
2367 rajveer 302
     * Checks weather entity is valid or not. Entity will be invalid in one of these cases:
303
     * <ol>
304
     * <li>The entity is not ready.
305
     * <li>The category has not been updated yet. (Set to -1).
306
     * <li>Content has not been updated after last content generation timestamp.
307
     * </ol>
308
     * 
309
     * @param entity
310
     * @return
311
     * @throws Exception
2171 rajveer 312
     */
2367 rajveer 313
    private boolean isValidEntity(Entity entity) throws Exception{
314
        ExpandedEntity expEntity = new ExpandedEntity(entity);
315
        EntityState state = CreationUtils.getEntityState(entity.getID());
316
        long categoryID = expEntity.getCategoryID();
317
 
318
        if(state.getStatus() != EntityStatus.READY ||  categoryID == -1){
319
            return false;
320
        }
321
        if(state.getMerkedReadyOn().getTime() < this.lastGenerationTime){
322
            return false;
323
        }
324
        return true;
325
    }
326
 
327
 
328
    private void populateEntityIdItemMap(){
2171 rajveer 329
        Date todate = new Date();
2367 rajveer 330
        for(Item item: items){
2171 rajveer 331
            //TODO Can be removed as we are checking in calling function
332
            if(!(item.getItemStatus()==status.ACTIVE || item.getItemStatus()==status.CONTENT_COMPLETE || item.getItemStatus() == status.PAUSED)){
333
                continue;
334
            }
335
            if(todate.getTime() < item.getStartDate()){
336
                continue;
337
            }
2367 rajveer 338
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
2171 rajveer 339
            if(itemList == null){
340
                itemList = new ArrayList<Item>();
341
            }
342
            itemList.add(item);
343
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
344
        }
2367 rajveer 345
 
346
        //Remove all items which have not been updated since last content generation.
2171 rajveer 347
        List<Long> removeEntities = new ArrayList<Long>();
348
        for(Long entityId:entityIdItemMap.keySet()){
349
            boolean isValidEntity = false;
2367 rajveer 350
            //If any one of the items has been updated before current timestamp, than we generate content for whole entity
2171 rajveer 351
            for(Item item: entityIdItemMap.get(entityId)){
2367 rajveer 352
                if(item.getUpdatedOn() > lastGenerationTime){
2171 rajveer 353
                    isValidEntity = true;
354
                }
355
            }
356
            if(!isValidEntity){
357
                removeEntities.add(entityId);
358
            }
359
        }
360
        for(Long entityId: removeEntities){
361
            entityIdItemMap.remove(entityId);
362
        }
363
    }
364
 
365
}