Subversion Repositories SmartDukaan

Rev

Rev 8809 | Rev 8811 | 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;
8810 amit.gupta 12
import in.shop2020.util.ContentGenerationUtility;
8749 amit.gupta 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;
46
    private static ContentViews views;
47
    private static StorageManager storageUtils;
48
    private static final Gson gs = new GsonBuilder().
49
    	registerTypeAdapter(BulletDataObject.class, new BDOAdapter()).
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();
97
    	dbo.put("categoryId", categoryId);
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();
8810 amit.gupta 203
    		log.info("Entity IDD :"  + (Long)dbo.get("_id"));
8749 amit.gupta 204
    		map.put((Long)dbo.get("_id"), (Entity)toObject(dbo, Entity.class));
205
    	}
206
    	return map;
207
    }
208
 
209
 
210
 
211
    /**
212
     * Returns all special pages from the database.
213
     */
214
    public Map<Long, SpecialPage> getSpecialPages() {
215
    	Map<Long,SpecialPage> map = new TreeMap<Long, SpecialPage>(); 
216
    	Iterator<DBObject> iterator = views.specialPages.find().iterator();
217
    	while(iterator.hasNext()){
218
    		DBObject dbo = iterator.next();
219
    		Long pageId = (Long)dbo.removeField("_id");
220
    		map.put(pageId, (SpecialPage)toObject(dbo, SpecialPage.class));
221
    	}
222
    	return map;
223
    }
224
 
225
    /**
226
     * Updates a given special page in the database.
227
     */
228
    public void updateSpecialPage(SpecialPage specialPage) {
229
    	insertOrUpdateById(views.specialPages, specialPage.getID(), specialPage);
230
    }
231
 
232
    /**
233
     * Returns a special page object given a id after looking it up from map
234
     * of values loaded from database.
235
     */
236
    public SpecialPage getSpecialPage(long specialPageId) {
237
        return (SpecialPage)getById(views.specialPages, specialPageId, SpecialPage.class);
238
    }
239
 
240
    /**
241
     * Removes a special page from database, if exists in database.
242
     */
243
    public void deleteSpecialPage(long specialPageId) {
244
    	removeById(views.specialPages, specialPageId);
245
    }
246
 
8750 amit.gupta 247
    @SuppressWarnings("unchecked")
8749 amit.gupta 248
    private static <T> T toObject(DBObject dbo, Type t) {
249
    	dbo.removeField("_id");
8751 amit.gupta 250
    	return (T)gs.fromJson(dbo.toString(), t);
8749 amit.gupta 251
    }
252
 
8750 amit.gupta 253
    @SuppressWarnings("unchecked")
8749 amit.gupta 254
    private static <T> T getById(DBCollection collection, Long id, Type t) {
255
    	DBObject dbo = collection.findOne(id);
256
    	if(dbo ==null) return null;
257
    	if (dbo.get(id.toString()) != null){
8751 amit.gupta 258
    		return (T)gs.fromJson(dbo.get(id.toString()).toString(), t);
8749 amit.gupta 259
    	}
260
    	dbo.removeField("_id");
8751 amit.gupta 261
    	return (T)gs.fromJson(dbo.toString(), t);
8749 amit.gupta 262
    }
263
 
8770 amit.gupta 264
    private static <T> void insertOrUpdateById  (DBCollection collection, long id, T obj) {
265
    	DBObject dbo = (DBObject)JSON.parse(gs.toJson(obj));
8749 amit.gupta 266
    	dbo.put("_id", id);
267
    	collection.update(new BasicDBObject("_id", id ), dbo, true, false);
268
 
269
    }
270
 
271
    private static void removeById(DBCollection collection, Long id) {
272
    	collection.remove(new BasicDBObject("_id", id));
273
    }
274
 
275
    public void storeDataObject(String dataObjectName, Object dataObject) throws Exception{
276
    	DBCollection collection = db.getCollection(dataObjectName);
277
    	Map <String, Object>  obj = new HashMap<String, Object>();
278
    	obj.put("1", dataObject);
279
    	insertOrUpdateById(collection, 1L, obj);
280
    }
281
 
8750 amit.gupta 282
    @SuppressWarnings("unchecked")
8749 amit.gupta 283
    public <T> T getDataObject(String dataObjectName, Type t) throws Exception{
284
    	DBCollection collection = db.getCollection(dataObjectName);
8751 amit.gupta 285
    	return (T)getById(collection, 1L, t);
8749 amit.gupta 286
    }
287
 
288
	public Long getMaxPageId() {
289
		Iterator<DBObject> dbo = views.specialPages.find().sort(new BasicDBObject("_id", -1)).limit(1).iterator();
290
		while  (dbo.hasNext()) {
291
			DBObject dbo1 = dbo.next();
292
			return (Long) dbo1.get("_id");
293
		}
294
		return 0l;
295
	}
296
 
297
	public void deleteEntity(long entityId) {
298
		removeById(views.entity, entityId);
299
		removeById(views.entityMetadata, entityId);
300
	}
301
 
302
	public void createEntity(Entity entity, EntityState entityMetadata) {
8770 amit.gupta 303
		insertOrUpdateById(views.entity, entity.getID(), entity);
304
		insertOrUpdateById(views.entityMetadata, entity.getID(), entityMetadata);
8749 amit.gupta 305
	}
306
 
307
	public void storeCustomSlideScores(long entityId, Map<Long, Double> customSlideScores) {
308
		insertOrUpdateById(views.customSlideScores, entityId, customSlideScores);
309
	}
310
 
311
	public Map<Long,Double> getCustomSlideScores(long entityId) {
312
		Type t = new TypeToken<Map<Long,Double>>() {}.getType();
313
		return getById(views.customSlideScores, entityId, t);
314
	}
315
 
316
	public void storeLearnedBullets( Map<Long, List<ExpandedBullet>> learnedBullets) {
317
 
318
		for(Map.Entry<Long, List<ExpandedBullet>> learnedBullet : learnedBullets.entrySet()) {
319
			insertOrUpdateById(views.learnedBullets, learnedBullet.getKey(), new BasicDBObject(learnedBullet.getKey().toString(), learnedBullet.getValue()));
320
		}
321
	}
322
 
323
 
8750 amit.gupta 324
	@SuppressWarnings("unchecked")
8749 amit.gupta 325
	public Map<Long, List<ExpandedBullet>> getLearnedBullets() {
326
		Type t = new TypeToken<List<ExpandedBullet>>() {}.getType();
327
		Map<Long, List<ExpandedBullet>> learnedBullets  = new HashMap<Long, List<ExpandedBullet>>();
328
		Iterator<DBObject> iter = views.learnedBullets.find();
329
		while (iter.hasNext()) {
330
			DBObject dbo = iter.next();
331
			String featureId = dbo.get("_id").toString();
332
			learnedBullets.put(Long.parseLong(featureId), (List<ExpandedBullet>)gs.fromJson(dbo.get(featureId).toString(), t));
333
		}
334
		return learnedBullets;
335
	}
336
 
337
	public Set<ExpandedBullet> getLearnedBulletsByFeatureId (long featureId){
338
		Type t = new TypeToken<Set<ExpandedBullet>>() {}.getType();
339
		return getById(views.learnedBullets, featureId, t);
340
	}
341
 
342
	public void storeExpertReview(long entityId, ExpertReview expertReview){
343
		Type t = new TypeToken<List<ExpertReview>>() {}.getType();
344
		List<ExpertReview> expertReviews = getById(views.expertReviews, entityId, t);
345
		expertReviews.add(expertReview);
346
		Map<Long,List<ExpertReview>> erMap = new HashMap<Long, List<ExpertReview>>();
347
		erMap.put(entityId, expertReviews);
348
		insertOrUpdateById(views.expertReviews, entityId, t);
349
 
350
	}
351
 
352
	public void storeSearchStats(Long date, Map<String,List<String>> searchTerms){
353
		insertOrUpdateById(views.searchStats, date, searchTerms);
354
	}
355
 
356
	public void deleteSearchStats(Long date){
357
		removeById(views.searchStats, date);
358
	}
359
 
360
	public List<String> getSearchStats(Long date){
361
		Type t = new TypeToken<List<String>>() {}.getType();
362
		return getById(views.searchStats, date, t);
363
	}
364
 
365
	public ExpertReviewSource getExpertReviewSource(long sourceId) {
366
		return getById(views.expertReviewSource, sourceId, ExpertReviewSource.class);
367
	}
368
 
369
	public Set<ExpertReviewSource> getExpertReviewSources() {
370
		Iterator<DBObject> sourcesObj = views.expertReviewSource.find().iterator();
371
		Set<ExpertReviewSource> expSources = new HashSet<ExpertReviewSource>();
372
		while(sourcesObj.hasNext()){
373
			DBObject dbobj = sourcesObj.next();
374
			expSources.add((ExpertReviewSource)toObject(dbobj, ExpertReviewSource.class));
375
		}
376
		return expSources;
377
	}
378
 
379
	public void storeExpertReviewSource(ExpertReviewSource expertReviewSource) {
380
		insertOrUpdateById(views.expertReviewSource, (long)expertReviewSource.hashCode(), expertReviewSource);
381
	}
382
 
383
	public void deleteExpertReviewSource(ExpertReviewSource expertReviewSource) {
384
		removeById(views.expertReviewSource, (long)expertReviewSource.hashCode());
385
	}
386
 
387
	public void storeExpertReview(long entityId, List<ExpertReview> expertReviews) {
388
		Map<Long, List<ExpertReview>> map = new HashMap<Long, List<ExpertReview>>();
389
		map.put(entityId, expertReviews);
390
		insertOrUpdateById(views.expertReviews, entityId, map);
391
	}
392
 
393
	public void deleteExpertReview(long entityId, int index) {
394
		Type t = new TypeToken<List<ExpertReview>>() {}.getType();
395
		List<ExpertReview> er = getById(views.expertReviews, entityId, t);
396
		er.remove(index);
397
		storeExpertReview(entityId, er);
398
	}
399
 
8750 amit.gupta 400
	@SuppressWarnings("unchecked")
8749 amit.gupta 401
	public Map<Long, List<ExpertReview>> getExpertReviews() {
402
		Type t = new TypeToken<List<ExpertReview>>() {}.getType();
403
		Map<Long, List<ExpertReview>> er  = new HashMap<Long, List<ExpertReview>>();
404
		Iterator<DBObject> iter = views.expertReviews.find();
405
		while (iter.hasNext()) {
406
			DBObject dbo = iter.next();
407
			String entityId = dbo.get("_id").toString();
408
			er.put(Long.parseLong(entityId), (List<ExpertReview>)gs.fromJson(dbo.get(entityId).toString(), t));
409
		}
410
		return er;
411
	}
412
 
413
	public void deleteExpertReview(long entityId) {
414
		removeById(views.expertReviews, entityId);
415
	}
416
 
417
 
8750 amit.gupta 418
	@SuppressWarnings("unchecked")
8749 amit.gupta 419
	public Map<Long, List<Long>> getHelpdocEntityIds() {
420
		Type t = new TypeToken<List<Long>>() {}.getType();
421
		Map<Long, List<Long>> er  = new HashMap<Long, List<Long>>();
422
		Iterator<DBObject> iter = views.helpdocEntityIds.find().iterator();
423
		while (iter.hasNext()) {
424
			DBObject dbo = iter.next();
425
			String helpdocId = dbo.get("_id").toString();
426
			er.put(Long.parseLong(helpdocId), (List<Long>)gs.fromJson(dbo.get(helpdocId).toString(), t));
427
		}
428
		return er;
429
	}
430
 
431
	public List<ExpertReview> getExpertReviewByEntity(long entityId) {
432
		Type t = new TypeToken<List<ExpertReview>>() {}.getType();
433
		return getById(views.expertReviews, entityId, t);
434
	}
435
 
436
}