source: ComponentRegistry/branches/jeaferversion/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/CommentsDao.java @ 1640

Last change on this file since 1640 was 1640, checked in by jeafer, 12 years ago

Jean-Charles branch ComponentRegistry commit5 (functionnal),
Changes regarding comment on the ComponentRegistry.

Modification of classes CommentsDao?
Response class has been split up. A general class ComponentRegistryResponse?
a abstractDescription response: RegisterResponse?
a comment response : CommentResponse?
Improvement of validation process for comments
Improvement of ComponentRegistryRestService?
New classes test CommentResponseTest? and CommentValidatorTest?

Documentation added to most classes
Clean up code in other classes

File size: 9.2 KB
Line 
1package clarin.cmdi.componentregistry.impl.database;
2
3import clarin.cmdi.componentregistry.model.Comment;
4
5import java.util.Date;
6import java.sql.ResultSet;
7import java.sql.SQLException;
8import java.sql.Timestamp;
9import java.text.ParseException;
10import java.util.HashMap;
11import java.util.List;
12import java.util.Map;
13import org.slf4j.Logger;
14import org.slf4j.LoggerFactory;
15import org.springframework.beans.factory.annotation.Autowired;
16import org.springframework.dao.DataAccessException;
17import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
18import org.springframework.jdbc.core.simple.ParameterizedSingleColumnRowMapper;
19import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
20import org.springframework.transaction.PlatformTransactionManager;
21import org.springframework.transaction.TransactionDefinition;
22import org.springframework.transaction.TransactionStatus;
23
24/**
25 *
26 * @author jean-charles FerriÚres <jean-charles.ferrieres@mpi.nl>
27 */
28public class CommentsDao extends ComponentRegistryDao<Comment> {
29
30    @Autowired
31    private PlatformTransactionManager txManager;
32    @Autowired
33    private TransactionDefinition txDefinition;
34    private final static Logger LOG = LoggerFactory.getLogger(CommentsDao.class);
35    private final static String SELECT_BASE = "SELECT " + COLUMN_ID + ", comments, comment_date, user_id, "
36            + "component_description_id, profile_description_id FROM " + TABLE_COMMENTS;
37
38    protected String getTableName() {
39        return TABLE_COMMENTS;
40    }
41
42    protected String getCMDIdColumn() {
43        return COLUMN_ID;
44    }
45
46    /**
47     * Get the list of all the comments available in the database
48     * The distinction between profile or component is not treated in this method
49     * @return list of Comments
50     */
51    public List<Comment> getAllComments() throws DataAccessException {
52        return getList(SELECT_BASE);
53    }
54
55    /**
56     * Look for a specified Comment through its id
57     * @param id Database record id (key)
58     * @return Comment, if it exists
59     * @throws DataAccessException
60     */
61    public Comment getById(String id) throws DataAccessException {
62        return getFirstOrNull(SELECT_BASE + " WHERE " + COLUMN_ID + " = ?", id);
63    }
64
65    /**
66     * Retrieve the comments related to a certain profile
67     * @param id Database record id (fkey)
68     * @return list of Comments
69     */
70    public List<Comment> getCommentsFromProfile(String profileId) throws DataAccessException {
71        return getList((SELECT_BASE + " WHERE profile_description_id = ?").concat(getOrderByDate()), profileId);
72    }
73
74    /**
75     * Retrieve a specific comment related to a profile
76     * @param id Database record id (key)
77     * @return Comment
78     * @throws DataAccessException
79     */
80    public Comment getSpecifiedCommentFromProfile(String commentId) throws DataAccessException {
81        return getFirstOrNull(SELECT_BASE + " WHERE " + COLUMN_ID + " = ?", Integer.parseInt(commentId));
82    }
83
84    /**
85     * Retrieve the comments related to a certain component
86     * @param id Database record id (fkey)
87     * @return list of Comments
88     * @throws DataAccessException
89     */
90    public List<Comment> getCommentsFromComponent(String componentId) throws DataAccessException {
91        return getList((SELECT_BASE + " WHERE component_description_id = ?").concat(getOrderByDate()), componentId);
92    }
93
94    /**
95     * Retrieve a specific comment related to a component
96     * @param id Database record id (key)
97     * @return Comment
98     * @throws DataAccessException
99     */
100    public Comment getSpecifiedCommentFromComponent(String commentId) throws DataAccessException {
101        return getFirstOrNull(SELECT_BASE + " WHERE " + COLUMN_ID + " =  ?", Integer.parseInt(commentId));
102    }
103
104    /**
105     *
106     * @param id
107     *            Id of description record
108     * @return Principal name of description's owner, if any. Otherwise, null.
109     */
110    public String getOwnerPrincipalName(Number id) {
111        StringBuilder select = new StringBuilder("SELECT principal_name FROM " + TABLE_REGISTRY_USER);
112        select.append(" JOIN ").append(getTableName());
113        select.append(" ON user_id = " + TABLE_REGISTRY_USER + ".id ");
114        select.append(" WHERE ").append(getTableName()).append(".id = ?");
115        List<String> owner = getSimpleJdbcTemplate().query(select.toString(), new ParameterizedSingleColumnRowMapper<String>(), id);
116        if (owner.isEmpty()) {
117            return null;
118        }
119        {
120            return owner.get(0);
121        }
122    }
123
124    /**
125     *
126     * @param comment
127     *              the comment to be inserted
128     * @param content
129     *             
130     * @param userId
131     *              the id of the user
132     * @return Record id of the inserted comment
133     * @throws DataAccessException
134     */
135    public Number insertComment(Comment comment, Number userId) throws DataAccessException {
136        TransactionStatus transaction = getTransaction();
137        try {
138            SimpleJdbcInsert insertComment = new SimpleJdbcInsert(getDataSource()).withTableName(getTableName()).usingGeneratedKeyColumns(COLUMN_ID);
139            Map<String, Object> params = new HashMap<String, Object>();
140            putInsertComment(params, comment, userId);
141
142            Number id = insertComment.executeAndReturnKey(params);
143            txManager.commit(transaction);
144            return id;
145        } catch (DataAccessException ex) {
146            txManager.rollback(transaction);
147            throw ex;
148        }
149    }
150
151    /**
152     *
153     * @param params
154     * @param comment
155     * @param contentId
156     * @param userId
157     * @throws DataAccessException
158     */
159    protected void putInsertComment(Map<String, Object> params, Comment comment, Number userId) throws DataAccessException {
160        params.put("comments", comment.getComment());
161        params.put("comment_date", extractTimestamp(comment));
162        params.put("component_description_id", comment.getComponentDescriptionId());
163        params.put("profile_description_id", comment.getProfileDescriptionId());
164        params.put("user_id", userId);
165    }
166
167    @Override
168    protected ParameterizedRowMapper<Comment> getRowMapper() {
169        return rowMapper;
170    }
171    private final ParameterizedRowMapper<Comment> rowMapper = new ParameterizedRowMapper<Comment>() {
172
173        @Override
174        public Comment mapRow(ResultSet rs, int rowNumber) throws SQLException {
175            Comment comment = new Comment();
176            Timestamp commentDate = rs.getTimestamp("comment_date");
177            comment.setId(rs.getString(COLUMN_ID));
178            comment.setComment(rs.getString("comments"));
179            comment.setComponentDescriptionId(rs.getString("component_description_id"));
180            comment.setProfileDescriptionId(rs.getString("profile_description_id"));
181            comment.setUserId(rs.getString("user_id"));
182            comment.setCommentDate(commentDate == null ? null : Comment.createNewDate(commentDate.getTime()));
183            return comment;
184        }
185    };
186
187    /**
188     * Method that will delete a comment from the database based on its id
189     * @param com
190     *           comment to be deleted
191     * @throws DataAccessException
192     */
193    public void deleteComment(Comment com) throws DataAccessException {
194        TransactionStatus transaction = getTransaction();
195        Number dbId = Integer.parseInt(com.getId());
196        StringBuilder delete = new StringBuilder("DELETE FROM ").append(getTableName());
197        delete.append(" WHERE " + COLUMN_ID + " = ?");
198        getSimpleJdbcTemplate().update(delete.toString(), dbId);
199        txManager.commit(transaction);
200    }
201
202    /**
203     * Retrieve comment Id From a comment
204     * @param cmdId
205     * @return query for database access to id
206     */
207    public Number getDbId(String cmdId) {
208        StringBuilder query = new StringBuilder("SELECT " + COLUMN_ID + " FROM ").append(getTableName());
209        query.append(" WHERE ").append(COLUMN_ID).append(" = ?");
210        return getSimpleJdbcTemplate().queryForInt(query.toString(), cmdId);
211    }
212
213    private Timestamp extractTimestamp(Comment comment) {
214        if (comment.getCommentDate() != null) {
215            try {
216                Date date = Comment.getDate(comment.getCommentDate());
217                return new Timestamp(date.getTime());
218            } catch (ParseException ex) {
219                LOG.warn("Could not convert registration date " + comment.getCommentDate() + " to date", ex);
220            } catch (IllegalArgumentException ex) {
221                LOG.warn("Could not convert registration date " + comment.getCommentDate() + " to timestamp", ex);
222            }
223        }
224        return null;
225    }
226
227    private TransactionStatus getTransaction() {
228        return txManager.getTransaction(txDefinition);
229    }
230
231    /**
232     * Method use for tests that will select comments based on the content
233     * @param aComment
234     * @return list of Comments
235     * @throws DataAccessException
236     */
237    public Comment getByComment(String aComment) throws DataAccessException {
238        return getFirstOrNull(SELECT_BASE + " WHERE comments = ?", aComment);
239    }
240   
241    /**
242     * Sort the returned comments per date from the most recent to the oldest
243     * @return
244     */
245        private String getOrderByDate() {
246        return " order by comment_date asc ";
247    }
248}
Note: See TracBrowser for help on using the repository browser.