Subversion Repositories SmartDukaan

Rev

Rev 22646 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
8749 amit.gupta 1
package in.shop2020.storage.mongo;
2
 
3
import in.shop2020.metamodel.core.BulletDataObject;
4
import in.shop2020.metamodel.core.Entity;
5
import in.shop2020.metamodel.core.EntityState;
6
import in.shop2020.metamodel.core.ExpertReview;
7
import in.shop2020.metamodel.core.ExpertReviewSource;
8
import in.shop2020.metamodel.core.Helpdoc;
9
import in.shop2020.metamodel.core.SpecialPage;
10
import in.shop2020.metamodel.util.ExpandedBullet;
11957 amit.gupta 11
import in.shop2020.metamodel.util.ItemPojo;
8749 amit.gupta 12
import in.shop2020.storage.mongo.adapters.BDOAdapter;
13
 
14
import java.lang.reflect.Type;
15
import java.util.ArrayList;
16
import java.util.Collection;
17
import java.util.HashMap;
18
import java.util.HashSet;
19
import java.util.Iterator;
20
import java.util.List;
21
import java.util.Map;
22
import java.util.Set;
23
import java.util.TreeMap;
24
 
8810 amit.gupta 25
import org.apache.commons.logging.Log;
26
import org.apache.commons.logging.LogFactory;
27
 
8749 amit.gupta 28
import com.google.gson.Gson;
29
import com.google.gson.GsonBuilder;
30
import com.google.gson.reflect.TypeToken;
31
import com.mongodb.BasicDBObject;
32
import com.mongodb.DB;
33
import com.mongodb.DBCollection;
34
import com.mongodb.DBObject;
35
import com.mongodb.MongoClient;
36
import com.mongodb.util.JSON;
37
 
38
/**
39
 * Entry point for storing everything in berkley database. Singleton class which initialises the berkley database.
40
 * @author rajveer
41
 *
42
 */
43
public class StorageManager {
8810 amit.gupta 44
	private static Log            log                         = LogFactory.getLog(StorageManager.class);
8749 amit.gupta 45
	private static DB db;
9218 amit.gupta 46
    public static ContentViews views;
8749 amit.gupta 47
    private static StorageManager storageUtils;
48
    private static final Gson gs = new GsonBuilder().
49
    	registerTypeAdapter(BulletDataObject.class, new BDOAdapter()).
8865 amit.gupta 50
    	//registerTypeAdapter(FreeformContent.class, new FFCAdapter()).
8749 amit.gupta 51
    	create();
52
 
53
    static{
54
		synchronized(StorageManager.class){
55
			try {
56
				storageUtils = new StorageManager("CONTENT");
57
			} catch (Exception e) {
58
				// TODO Auto-generated catch block
59
				e.printStackTrace();
60
			}
61
		}
62
	}
63
 
64
    /**
65
     * Run the sample program.
66
     * @throws Exception 
67
     */
68
    public static void main(String[] args) throws Exception {
11957 amit.gupta 69
    	String jsonDeals = StorageManager.getStorageManager().getDealsJson(1007521l);
70
    	System.out.println(jsonDeals);
8749 amit.gupta 71
    }
72
 
73
    /**
74
     * get storage manager
75
     * @return MongoStorageManager
76
     */
77
    public static StorageManager getStorageManager(){
78
		return storageUtils;
79
    }
80
 
81
    /**
82
     * Open the database and views.
83
     */
84
    private StorageManager(String mongoDB) throws Exception {
85
			MongoClient mongo = new MongoClient( "localhost" , 27017 );
86
			db = mongo.getDB(mongoDB);	
87
			views = ContentViews.getInstance(db);
88
    }
89
 
90
    /**
91
     * Get the entities for a given category
92
     * @param categoryId
93
     * @return Collection<Entity>
94
     */
95
    public Collection<Entity> getEntitisByCategory(long categoryId){
96
    	List <Entity> list = new ArrayList<Entity>();
97
    	DBObject dbo = new BasicDBObject();
8870 amit.gupta 98
    	dbo.put("categoryID", categoryId);
8749 amit.gupta 99
    	Iterator<DBObject> it = views.entity.find(dbo).iterator();
100
    	while (it.hasNext()) {
101
    		list.add((Entity)toObject(it.next(),Entity.class));
102
    	}
103
    	return list;
104
 
105
    }
106
 
107
 
108
    /**
109
     * get all helpdocs
110
     * @return
111
     */
112
	public Map<Long, Helpdoc> getHelpdocs(){
113
    	Map<Long, Helpdoc> helpdocs = new HashMap<Long, Helpdoc>();
114
    	Iterator<DBObject> iterator = views.helpdoc.find().iterator();
115
    	while (iterator.hasNext()){
116
    		DBObject dbo = iterator.next();
117
    		helpdocs.put((Long)dbo.get("_id"), (Helpdoc)toObject(dbo, Helpdoc.class));
118
    	}
119
    	return helpdocs;
120
    }
121
 
122
    /**
123
     * Get helpdoc for an given id
124
     * @param helpdocId
125
     * @return
126
     */
127
    public Helpdoc getHelpdoc(long helpdocId){
128
    	return getById(views.helpdoc, helpdocId, Helpdoc.class);
129
    }
130
 
131
    /**
132
     * Delete helpdoc for an given id
133
     * @param helpdocId
134
     * @return
135
     */
136
    public void deleteHelpdoc(long helpdocId){
137
    	views.helpdoc.remove(new BasicDBObject("_id", helpdocId));
138
    }
139
 
140
	public void updateHelpdoc(Helpdoc helpdoc){
141
    	insertOrUpdateById(views.helpdoc, helpdoc.getID(), helpdoc);
142
    }
143
 
144
	/**
145
     * get metadata for all entities
146
     * @return
147
     */
148
	public Map<Long, EntityState> getEntitiesMetadata(){
149
    	Map<Long,EntityState> es = new TreeMap<Long, EntityState>();
22646 amit.gupta 150
    	/*DBObject findDbo = new BasicDBObject().append(
151
                "$set", new BasicDBObject().append("id", 10000));*/
22645 amit.gupta 152
 
22646 amit.gupta 153
    	//Iterator<DBObject> iterator = views.entityMetadata.find(findDbo).iterator();
154
    	Iterator<DBObject> iterator = views.entityMetadata.find().iterator();
8749 amit.gupta 155
    	while (iterator.hasNext()){
156
    		DBObject dbo = iterator.next();
157
    		es.put((Long)dbo.get("_id"),(EntityState)toObject(dbo, EntityState.class));
158
    	}
159
    	return es;
160
    }
161
 
162
    /**
163
     * Get metadata for an given entity.
164
     * @param entityId
165
     * @return
166
     */
167
    public EntityState getEntityMetadata(long entityId){
168
    	return (EntityState)getById(views.entityMetadata, entityId, EntityState.class);
169
    }
170
 
171
    /**
172
     * update metadata for an given entity
173
     * @param entityMetadata
174
     */
175
	public void updateEntityMetadata(EntityState entityMetadata){
176
    	insertOrUpdateById(views.entityMetadata, entityMetadata.getID(), entityMetadata);
177
    }
178
 
179
    /**
180
     * Get entity for given id.
181
     * @param entityId
182
     * @return
183
     * @throws Exception
184
     */
185
    public Entity getEntity(long entityId) throws Exception{
186
    	return (Entity)getById(views.entity, entityId, Entity.class);
187
    }
188
 
189
    /**
190
     * Update an existing entity
191
     * @param entity
192
     * @throws Exception
193
     */
194
    public void updateEntity(Entity entity) throws Exception{
195
    	insertOrUpdateById(views.entity,entity.getID(),entity);
196
    }
197
 
198
    /**
199
     * Get all entities.
200
     * @return
201
     * @throws Exception
202
     */
203
	public Map<Long, Entity> getEntities() throws Exception{
204
    	Map<Long,Entity> map = new TreeMap<Long, Entity>(); 
205
    	Iterator<DBObject> iterator = views.entity.find().iterator();
206
    	while(iterator.hasNext()){
207
    		DBObject dbo = iterator.next();
208
    		map.put((Long)dbo.get("_id"), (Entity)toObject(dbo, Entity.class));
209
    	}
210
    	return map;
211
    }
212
 
213
 
214
 
215
    /**
216
     * Returns all special pages from the database.
217
     */
218
    public Map<Long, SpecialPage> getSpecialPages() {
219
    	Map<Long,SpecialPage> map = new TreeMap<Long, SpecialPage>(); 
220
    	Iterator<DBObject> iterator = views.specialPages.find().iterator();
221
    	while(iterator.hasNext()){
222
    		DBObject dbo = iterator.next();
223
    		Long pageId = (Long)dbo.removeField("_id");
224
    		map.put(pageId, (SpecialPage)toObject(dbo, SpecialPage.class));
225
    	}
226
    	return map;
227
    }
228
 
229
    /**
230
     * Updates a given special page in the database.
231
     */
232
    public void updateSpecialPage(SpecialPage specialPage) {
233
    	insertOrUpdateById(views.specialPages, specialPage.getID(), specialPage);
234
    }
235
 
236
    /**
237
     * Returns a special page object given a id after looking it up from map
238
     * of values loaded from database.
239
     */
240
    public SpecialPage getSpecialPage(long specialPageId) {
241
        return (SpecialPage)getById(views.specialPages, specialPageId, SpecialPage.class);
242
    }
243
 
244
    /**
245
     * Removes a special page from database, if exists in database.
246
     */
247
    public void deleteSpecialPage(long specialPageId) {
248
    	removeById(views.specialPages, specialPageId);
249
    }
250
 
8750 amit.gupta 251
    @SuppressWarnings("unchecked")
8749 amit.gupta 252
    private static <T> T toObject(DBObject dbo, Type t) {
253
    	dbo.removeField("_id");
8751 amit.gupta 254
    	return (T)gs.fromJson(dbo.toString(), t);
8749 amit.gupta 255
    }
256
 
8750 amit.gupta 257
    @SuppressWarnings("unchecked")
9218 amit.gupta 258
    public static <T> T getById(DBCollection collection, Long id, Type t) {
8749 amit.gupta 259
    	DBObject dbo = collection.findOne(id);
260
    	if(dbo ==null) return null;
261
    	if (dbo.get(id.toString()) != null){
8751 amit.gupta 262
    		return (T)gs.fromJson(dbo.get(id.toString()).toString(), t);
8749 amit.gupta 263
    	}
264
    	dbo.removeField("_id");
8751 amit.gupta 265
    	return (T)gs.fromJson(dbo.toString(), t);
8749 amit.gupta 266
    }
267
 
9218 amit.gupta 268
    public static <T> void insertOrUpdateById  (DBCollection collection, long id, T obj) {
8770 amit.gupta 269
    	DBObject dbo = (DBObject)JSON.parse(gs.toJson(obj));
8749 amit.gupta 270
    	dbo.put("_id", id);
271
    	collection.update(new BasicDBObject("_id", id ), dbo, true, false);
9218 amit.gupta 272
    }
273
 
274
    public static <T> void addById  (DBCollection collection, long id, T obj) {
275
    	DBObject dbo = (DBObject)JSON.parse(gs.toJson(obj));
8749 amit.gupta 276
 
9218 amit.gupta 277
    	//dbo.put("_id", id);
278
    	collection.update(new BasicDBObject("_id", id ), new BasicDBObject("$set", dbo), true, false);
8749 amit.gupta 279
    }
280
 
281
    private static void removeById(DBCollection collection, Long id) {
282
    	collection.remove(new BasicDBObject("_id", id));
283
    }
284
 
285
    public void storeDataObject(String dataObjectName, Object dataObject) throws Exception{
286
    	DBCollection collection = db.getCollection(dataObjectName);
287
    	Map <String, Object>  obj = new HashMap<String, Object>();
288
    	obj.put("1", dataObject);
289
    	insertOrUpdateById(collection, 1L, obj);
290
    }
291
 
8750 amit.gupta 292
    @SuppressWarnings("unchecked")
8749 amit.gupta 293
    public <T> T getDataObject(String dataObjectName, Type t) throws Exception{
294
    	DBCollection collection = db.getCollection(dataObjectName);
8751 amit.gupta 295
    	return (T)getById(collection, 1L, t);
8749 amit.gupta 296
    }
297
 
298
	public Long getMaxPageId() {
299
		Iterator<DBObject> dbo = views.specialPages.find().sort(new BasicDBObject("_id", -1)).limit(1).iterator();
300
		while  (dbo.hasNext()) {
301
			DBObject dbo1 = dbo.next();
302
			return (Long) dbo1.get("_id");
303
		}
304
		return 0l;
305
	}
306
 
307
	public void deleteEntity(long entityId) {
308
		removeById(views.entity, entityId);
309
		removeById(views.entityMetadata, entityId);
310
	}
311
 
312
	public void createEntity(Entity entity, EntityState entityMetadata) {
8770 amit.gupta 313
		insertOrUpdateById(views.entity, entity.getID(), entity);
314
		insertOrUpdateById(views.entityMetadata, entity.getID(), entityMetadata);
8749 amit.gupta 315
	}
316
 
317
	public void storeCustomSlideScores(long entityId, Map<Long, Double> customSlideScores) {
318
		insertOrUpdateById(views.customSlideScores, entityId, customSlideScores);
319
	}
320
 
321
	public Map<Long,Double> getCustomSlideScores(long entityId) {
322
		Type t = new TypeToken<Map<Long,Double>>() {}.getType();
323
		return getById(views.customSlideScores, entityId, t);
324
	}
325
 
326
	public void storeLearnedBullets( Map<Long, List<ExpandedBullet>> learnedBullets) {
327
 
328
		for(Map.Entry<Long, List<ExpandedBullet>> learnedBullet : learnedBullets.entrySet()) {
329
			insertOrUpdateById(views.learnedBullets, learnedBullet.getKey(), new BasicDBObject(learnedBullet.getKey().toString(), learnedBullet.getValue()));
330
		}
331
	}
332
 
333
 
8750 amit.gupta 334
	@SuppressWarnings("unchecked")
8749 amit.gupta 335
	public Map<Long, List<ExpandedBullet>> getLearnedBullets() {
336
		Type t = new TypeToken<List<ExpandedBullet>>() {}.getType();
337
		Map<Long, List<ExpandedBullet>> learnedBullets  = new HashMap<Long, List<ExpandedBullet>>();
338
		Iterator<DBObject> iter = views.learnedBullets.find();
339
		while (iter.hasNext()) {
340
			DBObject dbo = iter.next();
341
			String featureId = dbo.get("_id").toString();
342
			learnedBullets.put(Long.parseLong(featureId), (List<ExpandedBullet>)gs.fromJson(dbo.get(featureId).toString(), t));
343
		}
344
		return learnedBullets;
345
	}
346
 
347
	public Set<ExpandedBullet> getLearnedBulletsByFeatureId (long featureId){
348
		Type t = new TypeToken<Set<ExpandedBullet>>() {}.getType();
349
		return getById(views.learnedBullets, featureId, t);
350
	}
351
 
352
 
353
	public void storeSearchStats(Long date, Map<String,List<String>> searchTerms){
354
		insertOrUpdateById(views.searchStats, date, searchTerms);
355
	}
356
 
357
	public void deleteSearchStats(Long date){
358
		removeById(views.searchStats, date);
359
	}
360
 
361
	public List<String> getSearchStats(Long date){
362
		Type t = new TypeToken<List<String>>() {}.getType();
363
		return getById(views.searchStats, date, t);
364
	}
365
 
366
	public ExpertReviewSource getExpertReviewSource(long sourceId) {
367
		return getById(views.expertReviewSource, sourceId, ExpertReviewSource.class);
368
	}
369
 
370
	public Set<ExpertReviewSource> getExpertReviewSources() {
371
		Iterator<DBObject> sourcesObj = views.expertReviewSource.find().iterator();
372
		Set<ExpertReviewSource> expSources = new HashSet<ExpertReviewSource>();
373
		while(sourcesObj.hasNext()){
374
			DBObject dbobj = sourcesObj.next();
375
			expSources.add((ExpertReviewSource)toObject(dbobj, ExpertReviewSource.class));
376
		}
377
		return expSources;
378
	}
379
 
380
	public void storeExpertReviewSource(ExpertReviewSource expertReviewSource) {
381
		insertOrUpdateById(views.expertReviewSource, (long)expertReviewSource.hashCode(), expertReviewSource);
382
	}
383
 
384
	public void deleteExpertReviewSource(ExpertReviewSource expertReviewSource) {
385
		removeById(views.expertReviewSource, (long)expertReviewSource.hashCode());
386
	}
387
 
8905 amit.gupta 388
	public void storeExpertReview(long entityId, ExpertReview expertReview){
389
		Type t = new TypeToken<List<ExpertReview>>() {}.getType();
390
		List<ExpertReview> expertReviews = getById(views.expertReviews, entityId, t);
391
		if(expertReviews == null) {
392
			expertReviews = new ArrayList<ExpertReview>();
393
		}
394
		expertReviews.add(expertReview);
395
		Map<Long,List<ExpertReview>> erMap = new HashMap<Long, List<ExpertReview>>();
396
		erMap.put(entityId, expertReviews);
8906 amit.gupta 397
		insertOrUpdateById(views.expertReviews, entityId, erMap);
8905 amit.gupta 398
 
399
	}
400
 
8749 amit.gupta 401
	public void storeExpertReview(long entityId, List<ExpertReview> expertReviews) {
402
		Map<Long, List<ExpertReview>> map = new HashMap<Long, List<ExpertReview>>();
403
		map.put(entityId, expertReviews);
404
		insertOrUpdateById(views.expertReviews, entityId, map);
405
	}
406
 
407
	public void deleteExpertReview(long entityId, int index) {
408
		Type t = new TypeToken<List<ExpertReview>>() {}.getType();
409
		List<ExpertReview> er = getById(views.expertReviews, entityId, t);
410
		er.remove(index);
411
		storeExpertReview(entityId, er);
412
	}
413
 
8750 amit.gupta 414
	@SuppressWarnings("unchecked")
8749 amit.gupta 415
	public Map<Long, List<ExpertReview>> getExpertReviews() {
416
		Type t = new TypeToken<List<ExpertReview>>() {}.getType();
417
		Map<Long, List<ExpertReview>> er  = new HashMap<Long, List<ExpertReview>>();
418
		Iterator<DBObject> iter = views.expertReviews.find();
419
		while (iter.hasNext()) {
420
			DBObject dbo = iter.next();
421
			String entityId = dbo.get("_id").toString();
422
			er.put(Long.parseLong(entityId), (List<ExpertReview>)gs.fromJson(dbo.get(entityId).toString(), t));
423
		}
424
		return er;
425
	}
426
 
427
	public void deleteExpertReview(long entityId) {
428
		removeById(views.expertReviews, entityId);
429
	}
430
 
431
 
8750 amit.gupta 432
	@SuppressWarnings("unchecked")
8749 amit.gupta 433
	public Map<Long, List<Long>> getHelpdocEntityIds() {
434
		Type t = new TypeToken<List<Long>>() {}.getType();
435
		Map<Long, List<Long>> er  = new HashMap<Long, List<Long>>();
436
		Iterator<DBObject> iter = views.helpdocEntityIds.find().iterator();
437
		while (iter.hasNext()) {
438
			DBObject dbo = iter.next();
439
			String helpdocId = dbo.get("_id").toString();
440
			er.put(Long.parseLong(helpdocId), (List<Long>)gs.fromJson(dbo.get(helpdocId).toString(), t));
441
		}
442
		return er;
443
	}
444
 
445
	public List<ExpertReview> getExpertReviewByEntity(long entityId) {
446
		Type t = new TypeToken<List<ExpertReview>>() {}.getType();
447
		return getById(views.expertReviews, entityId, t);
448
	}
11957 amit.gupta 449
 
450
	public String getDealsJson(Long entityId){
451
		Type t = new TypeToken<ItemPojo>() {}.getType();
452
		DBObject dboQuery=  new BasicDBObject().append("_id", entityId);
11958 amit.gupta 453
		DBObject dboProjection = new BasicDBObject("items.dealPojo", 1);
11957 amit.gupta 454
		DBObject dbo =  views.siteContent.findOne(dboQuery,dboProjection);
455
		if(dbo != null && dbo.get("items")!=null){
456
			return dbo.get("items").toString();
457
		}
458
		return null;
459
	}
22647 amit.gupta 460
 
461
 
462
    public List<Long> getEntityIdsAfter(long time){
463
    	List <Long> list = new ArrayList<Long>();
464
    	Iterator<DBObject> it = StorageManager.views.entityMetadata.find(new BasicDBObject("$gt", new BasicDBObject("createdOn",time))).iterator();
465
    	while (it.hasNext()) {
466
    		EntityState emd = (EntityState)toObject(it.next(),EntityState.class);
467
    		list.add(emd.getID());
468
    	}
469
    	return list;
470
 
471
    }
8749 amit.gupta 472
 
473
}