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

Last change on this file since 1635 was 1635, checked in by jeafer, 13 years ago

Jean-Charles branch commit3,
Changes regarding comment on the ComponentRegistry service.
Delete_comment from RestService? to Database access (CommentsDao?) implemented.
Post_comment from RestService? to Database access (CommentsDao?) implemented. (Not yet tested)
Comment class updated
CommentsDao? updated
CommentTest? class implemented (New Class)
Test classes ComponentRegistryRestServiceTest? and RegistryHelperTest? starting to implement tests for Comment validation (insertion, deletion)

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