package org.itbelts.dao.mongolab; import java.lang.reflect.Type; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import org.itbelts.dao.ICourseDAO; import org.itbelts.dao.ITopicDAO; import org.itbelts.domain.Course; import org.itbelts.domain.Topic; import com.google.gson.reflect.TypeToken; /** * MongoDB implementation for the ICourseDAO. <br> * <br> * <u><i>Version History</i></u> * * <pre> * v2013.10.0 20-okt.-2013 - DKBR813 - initial release * * </pre> * * @version v2013.10.0 20-okt.-2013 * @author <a href=\"mailto:koenbruyndonckx@gmail.com\"> Koen Bruyndonckx </a> */ public class CourseDAOImpl extends AbstractMongoLabDAO implements ICourseDAO { private ITopicDAO myTopicDAO = new TopicDAOImpl(); private static final String PATH = "collections/courses"; @Override public List<Course> getCourses() { URL url = buildUrl( PATH, "f={\"_id\":1,\"topicId\":1,\"name\":1}" ); Type theListType = new TypeToken<List<Course>>() {}.getType(); return readFrom( url, theListType ); } @Override public List<Course> getCoursesForCommunity( String aCommunityId ) { // First get a complete list of all courses (we will filter out the ones we do not need later) List<Course> theFullList = getCourses(); // Build a small Map of topic-ids for all topics belonging to the given community Map<String,Boolean> theTopicMap = new HashMap<String,Boolean>(); List<Topic> theTopics = myTopicDAO.getTopicsForCommunity( aCommunityId ); for ( Topic t : theTopics ) { theTopicMap.put( t.get_id(), Boolean.TRUE ); } // Then remove all courses that have a topic id that is not in the Map for ( int i = theFullList.size() -1 ; i >= 0 ; i-- ) { String theTopicId = theFullList.get( i ).getTopicId(); if ( theTopicMap.get( theTopicId ) == null ) { theFullList.remove( i ); } } return theFullList; } @Override public Course getCourse( String aCourseId ) { URL url = buildUrl( PATH, "q={\"_id\":\"" + aCourseId + "\"}" ); Type theListType = new TypeToken<List<Course>>(){}.getType(); List<Course> theList = readFrom( url, theListType ); return theList.get( 0 ); } }