Subversion Repositories SmartDukaan

Rev

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