Subversion Repositories SmartDukaan

Rev

Rev 2367 | Rev 2433 | 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
 
2369 rajveer 128
	public boolean cleanDir(File dir, boolean deleteSelf) {
2367 rajveer 129
	    if (dir.isDirectory()) {
130
	        String[] children = dir.list();
131
	        for (int i=0; i<children.length; i++) {
2369 rajveer 132
	            boolean success = cleanDir(new File(dir, children[i]), true);
2367 rajveer 133
	            if (!success) {
134
	                return false;
135
	            }
136
	        }
137
	    }
138
	    // The directory is now empty so delete it
2369 rajveer 139
	    if(deleteSelf){
140
	    	return dir.delete();
141
	    }
142
	    return true;
2367 rajveer 143
	}
144
 
145
 
146
	private void removeOldResources() throws IOException{
147
		File f = new File(Utils.EXPORT_SOLR_PATH);
148
		if(f.exists()){
2369 rajveer 149
			cleanDir(f, false);
2367 rajveer 150
		}
151
 
152
		File f1 = new File(Utils.EXPORT_ENTITIES_PATH_LOCALHOST);
153
		if(f1.exists()){
2369 rajveer 154
			cleanDir(f1, false);
2367 rajveer 155
		}
156
 
157
		File f2 = new File(Utils.EXPORT_ENTITIES_PATH_SAHOLIC);
158
		if(f2.exists()){
2369 rajveer 159
			cleanDir(f2, false);
2367 rajveer 160
		}
161
 
162
		File f3 = new File(Utils.EXPORT_ENTITIES_PATH_SHOP2020);
163
		if(f3.exists()){
2369 rajveer 164
			cleanDir(f3, false);
2367 rajveer 165
		}
166
	}
167
 
168
    /**
169
     * Update the prices in the generated content
170
     * @throws Exception
171
     */
172
    private void updatePrices() throws Exception {
173
    	lastGenerationTime = new Long(0);
174
        if(GENERATION_TYPE.equals("ONE")) {
175
            items = client.getItemsByCatalogId(Long.parseLong(ENTITY_ID));
176
        }else{
177
            items = client.getAllItemsByStatus(status.ACTIVE);
178
            items.addAll(client.getAllItemsByStatus(status.PAUSED));
179
            items.addAll(client.getAllItemsByStatus(status.CONTENT_COMPLETE));
180
 
181
            //Clean up the data from the solr directories.
182
            removeOldResources();
183
 
184
        }
185
        //this still needs to be evolved. Must not be used.
186
        if(GENERATION_TYPE.equals("INCREMENTAL")) {
187
        }
188
 
189
 
2171 rajveer 190
 
2367 rajveer 191
        //Populate the entityIdIemMap 
192
        populateEntityIdItemMap();
193
 
194
        PriceInsertor priceInserter = new PriceInsertor();
195
 
196
        for(Map.Entry<Long, List<Item>> entry: entityIdItemMap.entrySet()){
197
        	long entityId = entry.getKey();
198
        	List<Item> items = entry.getValue();
199
            //TODO Domain name and destination  directory should be read from properties file
200
        	priceInserter.insertPriceInHtml(items, entityId, "saholic.com", Utils.EXPORT_ENTITIES_PATH_SAHOLIC);
201
        	priceInserter.insertPriceInHtml(items, entityId, "shop2020.in", Utils.EXPORT_ENTITIES_PATH_SHOP2020);
202
        	priceInserter.insertPriceInHtml(items, entityId, "localhost:8090", Utils.EXPORT_ENTITIES_PATH_LOCALHOST);
203
        	priceInserter.insertPriceInSolrData(entityId, getMinPrice(items));
204
            // Mark content-complete items as active after the content has been generated
205
        	for(Item item: items){
206
        		if(item.getItemStatus()==status.CONTENT_COMPLETE){
207
                    item.setItemStatus(status.ACTIVE);
208
                    item.setStatus_description("This item is active");
209
                    client.updateItem(item);
210
        		}
211
        	}
212
        }
213
 
214
        //Generate partners and json objects for phones only
215
        if(!GENERATION_TYPE.equals("ONE")) {
216
        	ProductListGenerator generator = new ProductListGenerator(entityIdItemMap);
217
			generator.generateProductsListXML();
218
			generator.generateProductListJavascript();
219
        }
220
 
2171 rajveer 221
    }
222
 
2367 rajveer 223
 
2171 rajveer 224
    /**
2367 rajveer 225
     * 
226
     * @param items
227
     * @return the minimum price of the items
228
     */
229
	private double getMinPrice(List<Item> items){
230
        double minPrice = Double.MAX_VALUE;
231
        for(Item item: items){
232
            if(minPrice > item.getSellingPrice()){
233
                minPrice = item.getSellingPrice();
234
            }
235
        }
236
        return minPrice;
237
    }
238
 
239
 
240
	/**
2171 rajveer 241
     * Generates content for the specified entity embedding links to the
242
     * specified domain name.
243
     * 
2367 rajveer 244
     * The method will not generate content if one of the following conditions is met:
2171 rajveer 245
     * <ol>
246
     * <li>The entity is not ready.
247
     * <li>The category has not been updated yet. (Set to -1).
2367 rajveer 248
     * <li>The content has not been updated.
2171 rajveer 249
     * </ol>
2367 rajveer 250
     *
251
     * @throws
2171 rajveer 252
     */
253
    private void generateContent() throws Exception{
2367 rajveer 254
        if(GENERATION_TYPE.equals("ALL")) {
255
        	entities = CreationUtils.getEntities();
256
            lastGenerationTime = new Long(0);
257
        }else if(GENERATION_TYPE.equals("ONE")) {
258
        	entities = new HashMap<Long, Entity>();
259
        	entities.put(Long.parseLong(ENTITY_ID), CreationUtils.getEntity(Long.parseLong(ENTITY_ID)));
2171 rajveer 260
            lastGenerationTime = new Long(0);   
261
        }else{
2367 rajveer 262
        	entities = CreationUtils.getEntities();
2171 rajveer 263
            lastGenerationTime = CreationUtils.getLastContentGenerationTime();
264
            if(lastGenerationTime==null){
265
                lastGenerationTime = new Long(0);
266
            }    
267
        }
2367 rajveer 268
        //Filter invalid entities here
269
        List<Entity> validEntities = new ArrayList<Entity>();
270
        for(long entityID: entities.keySet()){
271
        	if(isValidEntity(entities.get(entityID))){
272
        		validEntities.add(entities.get(entityID));
273
        	}
2171 rajveer 274
        }
2367 rajveer 275
        //Calculate comparison scores
276
        NewCMP cmp = new NewCMP(validEntities);
2171 rajveer 277
        Map<Long, Map<Long, Double>> slideScoresByEntity = cmp.getSlideScores();
2367 rajveer 278
        CreationUtils.storeSlideScores(slideScoresByEntity);
2171 rajveer 279
 
280
        NewVUI vui = new NewVUI(lastGenerationTime);
2367 rajveer 281
        for(Entity entity: validEntities){
282
        		vui.generateHtmlForOneEntity(entity, Utils.EXPORT_VELOCITY_PATH);
2171 rajveer 283
        }
2367 rajveer 284
        CreationUtils.storeLastContentGenerationTime((new Date()).getTime());
285
 
286
 
287
        NewIR ir = new NewIR(validEntities);
2227 rajveer 288
        ir.exportIRData();
2367 rajveer 289
        //ir.transformIrDataXMLtoSolrXML();
2227 rajveer 290
        ir.exportIRMetaData();
291
        ir.transformIrMetaDataXMLSolrSchemaXML();
292
 
2171 rajveer 293
    }
2367 rajveer 294
 
2171 rajveer 295
 
296
    /**
2367 rajveer 297
     * Checks weather entity is valid or not. Entity will be invalid in one of these cases:
298
     * <ol>
299
     * <li>The entity is not ready.
300
     * <li>The category has not been updated yet. (Set to -1).
301
     * <li>Content has not been updated after last content generation timestamp.
302
     * </ol>
303
     * 
304
     * @param entity
305
     * @return
306
     * @throws Exception
2171 rajveer 307
     */
2367 rajveer 308
    private boolean isValidEntity(Entity entity) throws Exception{
309
        ExpandedEntity expEntity = new ExpandedEntity(entity);
310
        EntityState state = CreationUtils.getEntityState(entity.getID());
311
        long categoryID = expEntity.getCategoryID();
312
 
313
        if(state.getStatus() != EntityStatus.READY ||  categoryID == -1){
314
            return false;
315
        }
316
        if(state.getMerkedReadyOn().getTime() < this.lastGenerationTime){
317
            return false;
318
        }
319
        return true;
320
    }
321
 
322
 
323
    private void populateEntityIdItemMap(){
2171 rajveer 324
        Date todate = new Date();
2367 rajveer 325
        for(Item item: items){
2171 rajveer 326
            //TODO Can be removed as we are checking in calling function
327
            if(!(item.getItemStatus()==status.ACTIVE || item.getItemStatus()==status.CONTENT_COMPLETE || item.getItemStatus() == status.PAUSED)){
328
                continue;
329
            }
330
            if(todate.getTime() < item.getStartDate()){
331
                continue;
332
            }
2367 rajveer 333
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
2171 rajveer 334
            if(itemList == null){
335
                itemList = new ArrayList<Item>();
336
            }
337
            itemList.add(item);
338
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
339
        }
2367 rajveer 340
 
341
        //Remove all items which have not been updated since last content generation.
2171 rajveer 342
        List<Long> removeEntities = new ArrayList<Long>();
343
        for(Long entityId:entityIdItemMap.keySet()){
344
            boolean isValidEntity = false;
2367 rajveer 345
            //If any one of the items has been updated before current timestamp, than we generate content for whole entity
2171 rajveer 346
            for(Item item: entityIdItemMap.get(entityId)){
2367 rajveer 347
                if(item.getUpdatedOn() > lastGenerationTime){
2171 rajveer 348
                    isValidEntity = true;
349
                }
350
            }
351
            if(!isValidEntity){
352
                removeEntities.add(entityId);
353
            }
354
        }
355
        for(Long entityId: removeEntities){
356
            entityIdItemMap.remove(entityId);
357
        }
358
    }
359
 
360
}