001/*
002 *  Copyright 2011 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.survey.data;
017
018import java.sql.Connection;
019import java.sql.SQLException;
020import java.util.Collections;
021import java.util.HashMap;
022import java.util.List;
023import java.util.Map;
024
025import org.apache.ibatis.session.SqlSession;
026
027import org.ametys.core.datasource.AbstractMyBatisDAO;
028import org.ametys.core.datasource.ConnectionHelper;
029import org.ametys.core.user.UserIdentity;
030
031/**
032 * Survey answer DAO.
033 */
034public class SurveyAnswerDao extends AbstractMyBatisDAO
035{
036    /** The Avalon role name. */
037    public static final String ROLE = SurveyAnswerDao.class.getName();
038    
039    /**
040     * Get a session from its ID.
041     * @param sessionId the session ID.
042     * @return the session.
043     */
044    public SurveySession getSession(int sessionId)
045    {
046        Map<String, Object> params = new HashMap<>();
047        params.put("id", sessionId);
048        
049        try (SqlSession session = getSession())
050        {
051            return (SurveySession) session.selectOne("SurveyAnswer.getSession", params);
052        }
053    }
054    
055    /**
056     * Get a user session from the survey ID and the user identity.
057     * @param surveyId the survey ID.
058     * @param user the user.
059     * @return the session.
060     */
061    public SurveySession getSession(String surveyId, UserIdentity user)
062    {
063        Map<String, Object> params = new HashMap<>();
064        params.put("surveyId", surveyId);
065        params.put("login", user.getLogin());
066        params.put("population", user.getPopulationId());
067        
068        try (SqlSession sqlSession = getSession())
069        {
070            List<SurveySession> sessions = sqlSession.selectList("SurveyAnswer.getUserSession", params);
071            SurveySession session = sessions != null && !sessions.isEmpty() ? sessions.get(0) : null;
072            return session;
073        }
074    }
075    
076    /**
077     * Get a session from its ID.
078     * @param sessionId the session ID.
079     * @return the session.
080     */
081    public SurveySession getSessionWithAnswers(int sessionId)
082    {
083        Map<String, Object> params = new HashMap<>();
084        params.put("id", sessionId);
085        
086        try (SqlSession session = getSession())
087        {
088            return (SurveySession) session.selectOne("SurveyAnswer.getSessionWithAnswers", params);
089        }
090    }
091    
092    /**
093     * Get the count of sessions for a given survey.
094     * @param surveyId the survey ID.
095     * @return the session count for this survey.
096     */
097    public int getSessionCount(String surveyId)
098    {
099        Map<String, Object> params = new HashMap<>();
100        params.put("surveyId", surveyId);
101        
102        try (SqlSession session = getSession())
103        {
104            return (Integer) session.selectOne("SurveyAnswer.getSessionCount", params);
105        }
106    }
107    
108    /**
109     * Get the session count list.
110     * @return the session count list.
111     */
112    public List<Map<String, Object>> getAllSessionCount()
113    {
114        try (SqlSession session = getSession())
115        {
116            return session.selectList("SurveyAnswer.getAllSessionCount");
117        }
118    }
119    
120    /**
121     * Get the exhaustive list of sessions.
122     * @return the sessions.
123     */
124    public List<SurveySession> getSessions()
125    {
126        try (SqlSession session = getSession())
127        {
128            return session.selectList("SurveyAnswer.getSessions", Collections.EMPTY_MAP);
129        }
130    }
131    
132    /**
133     * Get all the sessions of a given survey.
134     * @param surveyId the survey ID.
135     * @return the sessions.
136     */
137    public List<SurveySession> getSessions(String surveyId)
138    {
139        Map<String, Object> params = new HashMap<>();
140        params.put("surveyId", surveyId);
141        
142        try (SqlSession session = getSession())
143        {
144            return session.selectList("SurveyAnswer.getSessions", params);
145        }
146    }
147    
148    /**
149     * Get all the sessions of a given survey, with their answers.
150     * @param surveyId the survey ID.
151     * @return the sessions with their answers.
152     */
153    public List<SurveySession> getSessionsWithAnswers(String surveyId)
154    {
155        Map<String, Object> params = new HashMap<>();
156        params.put("surveyId", surveyId);
157        
158        try (SqlSession session = getSession())
159        {
160            return session.selectList("SurveyAnswer.getSessionsWithAnswers", params);
161        }
162    }
163    
164    /**
165     * Get the answers of a session.
166     * @param sessionId the session ID.
167     * @return the session answers.
168     */
169    public List<SurveyAnswer> getAnswers(int sessionId)
170    {
171        Map<String, Object> params = new HashMap<>();
172        params.put("sessionId", sessionId);
173        
174        try (SqlSession session = getSession())
175        {
176            return session.selectList("SurveyAnswer.getAnswers", params);
177        }
178    }
179    
180    /**
181     * Insert a session with its answers.
182     * @param session the session.
183     * @throws SQLException if a database access error occurs
184     */
185    public void addSession(SurveySession session) throws SQLException
186    {
187        try (SqlSession sqlSession = getSession())
188        {
189            try (Connection connection = sqlSession.getConnection())
190            {
191                String stmtId = "SurveyAnswer.addSession" + getStatementSuffix(connection);
192                
193                // Insert the session object and get the generated ID.
194                sqlSession.insert(stmtId, session);
195                
196                int sessionId = session.getId();
197                
198                Map<String, Object> params = new HashMap<>();
199                params.put("sessionId", sessionId);
200                
201                // Insert each answer.
202                for (SurveyAnswer answer : session.getAnswers())
203                {
204                    params.put("questionId", answer.getQuestionId());
205                    params.put("answer", answer.getValue());
206                    
207                    sqlSession.insert("SurveyAnswer.addAnswer", params);
208                }
209                
210                // Commit the transaction.
211                sqlSession.commit();
212            }
213        }
214    }
215    
216    /**
217     * Delete a session with its answers.
218     * @param sessionId the session ID.
219     */
220    public void deleteSession(String sessionId)
221    {
222        try (SqlSession session = getSession())
223        {
224            // Delete the answers.
225            session.delete("SurveyAnswer.deleteAnswers", sessionId);
226            
227            // Delete the session itself.
228            session.delete("SurveyAnswer.deleteSession", sessionId);
229            
230            // Commit the transaction.
231            session.commit();
232        }
233    }
234    
235    /**
236     * Delete sessions related to a given survey.
237     * @param surveyId the survey ID.
238     */
239    public void deleteSessions(String surveyId)
240    {
241        try (SqlSession session = getSession())
242        {
243            // Delete the answers.
244            session.delete("SurveyAnswer.deleteSurveyAnswers", surveyId);
245            
246            // Delete the sessions.
247            session.delete("SurveyAnswer.deleteSurveySessions", surveyId);
248            
249            // Commit the transaction.
250            session.commit();
251        }
252    }
253    
254    /**
255     * Get the statement name suffix, depending of the DBMS family.
256     * @param connection the connection.
257     * @return the statement suffix.
258     */
259    protected String getStatementSuffix(Connection connection)
260    {
261        String dbType = ConnectionHelper.getDatabaseType(connection);
262        switch (dbType)
263        {
264            case ConnectionHelper.DATABASE_MYSQL:
265                return "-mysql";
266            case ConnectionHelper.DATABASE_POSTGRES:
267                return "-postgresql";
268            case ConnectionHelper.DATABASE_ORACLE:
269                return "-oracle";
270            case ConnectionHelper.DATABASE_DERBY:
271                return "-derby";
272            default:
273                return "";
274        }
275    }
276}