source: DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/JdbcAnnotationDao.java @ 3475

Last change on this file since 3475 was 3475, checked in by olhsha, 11 years ago

making javadoc comments for signatures in all dao-s (except dispatcher)

File size: 16.1 KB
Line 
1/*
2 * Copyright (C) 2013 DASISH
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17 */
18package eu.dasish.annotation.backend.dao.impl;
19
20import eu.dasish.annotation.backend.Helpers;
21import eu.dasish.annotation.backend.dao.AnnotationDao;
22import eu.dasish.annotation.schema.Annotation;
23import eu.dasish.annotation.schema.AnnotationInfo;
24import eu.dasish.annotation.schema.Permission;
25import eu.dasish.annotation.schema.ResourceREF;
26import java.lang.String;
27import java.sql.ResultSet;
28import java.sql.SQLException;
29import java.sql.Timestamp;
30import java.util.ArrayList;
31import java.util.HashMap;
32import java.util.List;
33import java.util.Map;
34import java.util.UUID;
35import javax.sql.DataSource;
36import javax.xml.datatype.DatatypeConfigurationException;
37import org.springframework.jdbc.core.RowMapper;
38
39/**
40 * Created on : Jun 27, 2013, 10:30:52 AM
41 *
42 * @author Peter Withers <peter.withers@mpi.nl>
43 */
44public class JdbcAnnotationDao extends JdbcResourceDao implements AnnotationDao {
45
46   
47    public JdbcAnnotationDao(DataSource dataSource) {
48        setDataSource(dataSource);
49        internalIdName = annotation_id;
50        resourceTableName = annotationTableName;
51       
52    }
53   
54   
55    ///////////// GETTERS /////////////
56 
57    @Override
58    public List<Number> retrieveSourceIDs(Number annotationID) {
59        StringBuilder sql = new StringBuilder("SELECT DISTINCT ");
60        sql.append(source_id).append(" FROM ").append(annotationsSourcesTableName).append(" WHERE ").append(annotation_id).append("= ?");
61        return getSimpleJdbcTemplate().query(sql.toString(), sourceIDRowMapper, annotationID);
62    }
63   
64
65    ////////////////////////////////////////////////////////////////////////
66    @Override
67    public List<Number> getFilteredAnnotationIDs(List<Number> annotationIDs, String text, String access, String namespace, Number ownerID, Timestamp after, Timestamp before) {
68
69        StringBuilder sql = new StringBuilder("SELECT DISTINCT ");
70        sql.append(annotation_id).append(" FROM ").append(annotationTableName).append(" WHERE TRUE ");
71        Map<String, Object> params = new HashMap<String, Object>();
72
73        if (annotationIDs == null) {
74            return null;
75        } else {
76            if (annotationIDs.isEmpty()) {
77                return new ArrayList<Number>();
78            }
79        }
80
81        String values = makeListOfValues(annotationIDs);
82        sql.append(" AND ").append(annotation_id).append(" IN ").append(values);
83
84
85        if (ownerID != null) {
86            sql.append(" AND ").append(owner_id).append(" = :owner ");
87            params.put("owner", ownerID);
88        }
89
90        if (after != null) {
91            sql.append(" AND ").append(time_stamp).append("  > :after");
92            params.put("after", after);
93        }
94
95        if (before != null) {
96            sql.append(" AND ").append(time_stamp).append("  < :before");
97            params.put("before", before);
98        }
99
100        if (text != null) {
101            sql.append(" AND ").append(body_xml).append("  LIKE '%").append(text).append("%'");
102        }
103
104        return getSimpleJdbcTemplate().query(sql.toString(), internalIDRowMapper, params);
105    }
106
107    //////////////////////////////
108    @Override
109    public List<Number> retrieveAnnotationList(List<Number> sourceIDs) {
110        if (sourceIDs == null) {
111            return null;
112        }
113        if (sourceIDs.isEmpty()) {
114            return new ArrayList<Number>();
115        }
116        String values = makeListOfValues(sourceIDs);
117        StringBuilder query = new StringBuilder("SELECT DISTINCT ");
118        query.append(annotation_id).append(" FROM ").append(annotationsSourcesTableName).append(" WHERE ").append(source_id).append(" IN ");
119        query.append(values);
120        return getSimpleJdbcTemplate().query(query.toString(), internalIDRowMapper);
121    }
122   
123    //////////////////////////////////////////////////////////////////////////
124
125    @Override
126    public List<AnnotationInfo> getAnnotationInfos(List<Number> annotationIDs) {
127
128        if (annotationIDs == null) {
129            return null;
130        }
131
132        if (annotationIDs.isEmpty()) {
133            return (new ArrayList<AnnotationInfo>());
134        }
135
136        String values = makeListOfValues(annotationIDs);
137        StringBuilder sql = new StringBuilder("SELECT DISTINCT ");
138        sql.append(annotationStar).append(" FROM ").append(annotationTableName ).append(" WHERE ").append(annotationAnnotation_id).append("  IN ").append(values);
139        return getSimpleJdbcTemplate().query(sql.toString(), annotationInfoRowMapper);
140    }
141    private final RowMapper<AnnotationInfo> annotationInfoRowMapper = new RowMapper<AnnotationInfo>() {
142        @Override
143        public AnnotationInfo mapRow(ResultSet rs, int rowNumber) throws SQLException {
144            AnnotationInfo annotationInfo = new AnnotationInfo();
145            annotationInfo.setRef(externalIDtoURI(_serviceURI, rs.getString(external_id)));
146            annotationInfo.setOwner(getResourceREF(Integer.toString(rs.getInt(owner_id))));
147            annotationInfo.setHeadline(rs.getString(headline));
148            return annotationInfo;
149        }
150    };
151
152    /////////////////////////////////////////////////
153    /**
154     *
155     * @param annotationIDs
156     * @return list of annotation references corresponding to the annotation-ids
157     * from the input list if the input list is null or empty (zero elements)
158     * returns an empty list there may be annotationIDs which are not in the DB
159     * (so that's why we need this method).
160     */
161    @Override
162    public List<ResourceREF> getAnnotationREFs(List<Number> annotationIDs) {
163        if (annotationIDs == null) {
164            return null;
165        }
166        if (annotationIDs.isEmpty()) {
167            return (new ArrayList<ResourceREF>());
168        }
169
170        String values = makeListOfValues(annotationIDs);
171        StringBuilder sql = new StringBuilder("SELECT DISTINCT ");
172        sql.append(external_id).append(" FROM ").append(annotationTableName).append(" WHERE ").append(annotationAnnotation_id).append("  IN ").append(values);
173        return getSimpleJdbcTemplate().query(sql.toString(), annotationREFRowMapper);
174    }
175    private final RowMapper<ResourceREF> annotationREFRowMapper = new RowMapper<ResourceREF>() {
176        @Override
177        public ResourceREF mapRow(ResultSet rs, int rowNumber) throws SQLException {
178            ResourceREF annotationREF = new ResourceREF();
179            annotationREF.setRef(externalIDtoURI(_serviceURI, rs.getString(external_id)));
180            return annotationREF;
181        }
182    };
183
184    //////////////////////////////////////////////////////////////////////////
185    @Override   
186    public Annotation getAnnotationWithoutSources(Number annotationID) throws SQLException {
187        if (annotationID == null) {
188            return null;        }
189        StringBuilder sql = new StringBuilder("SELECT ");
190        sql.append(annotationStar).append(" FROM ").append(annotationTableName).append(" WHERE ").append(annotationAnnotation_id).append("= ? LIMIT  1");
191        List<Annotation> respond = getSimpleJdbcTemplate().query(sql.toString(), annotationRowMapper, annotationID);
192        return (respond.isEmpty() ? null : respond.get(0));
193    }
194   
195    private final RowMapper<Annotation> annotationRowMapper = new RowMapper<Annotation>() {
196        @Override
197        public Annotation mapRow(ResultSet rs, int rowNumber) throws SQLException {
198            Annotation annotation = new Annotation();
199
200            ResourceREF ownerREF = new ResourceREF();
201            ownerREF.setRef(String.valueOf(rs.getInt(owner_id)));
202            annotation.setOwner(ownerREF);
203
204            annotation.setHeadline(rs.getString(headline));
205
206            annotation.setBody(Helpers.deserializeBody(rs.getString(body_xml)));
207            annotation.setTargetSources(null);
208            annotation.setURI(externalIDtoURI(_serviceURI, rs.getString(external_id)));
209
210            try {
211                annotation.setTimeStamp(Helpers.setXMLGregorianCalendar(rs.getTimestamp(time_stamp)));
212                return annotation;
213            } catch (DatatypeConfigurationException e) {
214                System.out.println(e);
215                return annotation; // no date-time is set
216            }
217        }
218    };
219   
220   /////////////////////////////
221    @Override
222    public boolean annotationIsInUse(Number annotationID) {
223        StringBuilder sqlNotebooks = new StringBuilder("SELECT ");
224        sqlNotebooks.append(notebook_id).append(" FROM ").append(notebooksAnnotationsTableName).append(" WHERE ").append(annotation_id).append("= ? LIMIT 1");
225        List<Number> resultNotebooks = getSimpleJdbcTemplate().query(sqlNotebooks.toString(), notebookIDRowMapper, annotationID);
226        if (resultNotebooks.size() > 0) {
227            return true;
228        }
229       
230        StringBuilder sqlSources = new StringBuilder("SELECT ");
231        sqlSources.append(source_id).append(" FROM ").append(annotationsSourcesTableName).append(" WHERE ").append(annotation_id).append("= ? LIMIT 1");
232        List<Number> resultSources = getSimpleJdbcTemplate().query(sqlSources.toString(), sourceIDRowMapper, annotationID);
233        if (resultSources.size() > 0) {
234            return true;
235        }
236       
237        StringBuilder sqlPermissions = new StringBuilder("SELECT ");
238        sqlPermissions.append(principal_id).append(" FROM ").append(permissionsTableName).append(" WHERE ").append(annotation_id).append("= ? LIMIT 1");
239        List<Number> resultPermissions = getSimpleJdbcTemplate().query(sqlPermissions.toString(), principalIDRowMapper, annotationID);
240        return (resultPermissions.size() > 0);
241    }
242   
243    //////////// UPDATERS /////////////
244   
245   
246    @Override
247    public int updateBody(Number annotationID, String serializedNewBody) {
248        StringBuilder sql = new StringBuilder("UPDATE ");
249        sql.append(annotationTableName).append(" SET ").append(body_xml).append("= '").append(serializedNewBody).append("' WHERE ").append(annotation_id).append("= ?");
250        return getSimpleJdbcTemplate().update(sql.toString(), annotationID);
251    }
252
253   
254
255 
256   
257    //////////// ADDERS ////////////////////////
258   
259   
260    @Override
261    public Number addAnnotation(Annotation annotation, Number ownerID) throws SQLException {
262        // generate a new annotation ID
263        UUID externalID = UUID.randomUUID();
264        Map<String, Object> params = new HashMap<String, Object>();
265        params.put("externalId", externalID.toString());
266        params.put("ownerId", ownerID);
267        params.put("headline", annotation.getHeadline());
268        params.put("bodyXml", annotation.getBody().getAny().get(0).toString());
269
270        StringBuilder sql = new StringBuilder("INSERT INTO ");
271        sql.append(annotationTableName).append("(").append(external_id).append(",").append(owner_id);
272        sql.append(",").append(headline).append(",").append(body_xml).append(" ) VALUES (:externalId, :ownerId, :headline, :bodyXml)");
273        int affectedRows = getSimpleJdbcTemplate().update(sql.toString(), params);
274        return ((affectedRows > 0) ? getInternalID(externalID) : null);
275    }
276   
277    //////////////////////////////////////////////////////////////////////////////////
278    @Override
279    public int addAnnotationSourcePair(Number annotationID, Number sourceID) throws SQLException {
280        Map<String, Object> paramsAnnotationsSources = new HashMap<String, Object>();
281        paramsAnnotationsSources.put("annotationId", annotationID);
282        paramsAnnotationsSources.put("sourceId", sourceID);
283        StringBuilder  sqlAnnotationsSources = new StringBuilder("INSERT INTO ");
284        sqlAnnotationsSources.append(annotationsSourcesTableName ).append("(").append(annotation_id).append(",").append(source_id).append(" ) VALUES (:annotationId, :sourceId)");
285        return getSimpleJdbcTemplate().update(sqlAnnotationsSources.toString(), paramsAnnotationsSources);
286    }
287    //////////////////////////////////////////////////////////////////////////////////
288
289   
290    /////////////////// DELETERS //////////////////////////
291    @Override
292    public int deleteAnnotation(Number annotationID) throws SQLException {
293        if (annotationIsInUse(annotationID)) {
294            return 0;
295        }
296        StringBuilder sqlAnnotation = new StringBuilder("DELETE FROM ");
297        sqlAnnotation.append(annotationTableName).append(" where ").append(annotation_id).append(" = ?");
298        return (getSimpleJdbcTemplate().update(sqlAnnotation.toString(), annotationID)); 
299    }
300   
301    //////////////////////////////////////////////////////
302    @Override
303    public int deleteAllAnnotationSource(Number annotationID) throws SQLException {
304        StringBuilder sqlTargetSources = new StringBuilder("DELETE FROM ");
305        sqlTargetSources.append(annotationsSourcesTableName).append(" WHERE ").append(annotation_id).append(" = ?");
306        return getSimpleJdbcTemplate().update(sqlTargetSources.toString(), annotationID); // # removed "annotations_target_sources" rows
307       
308    }
309   
310
311 
312   
313    /////////////// helpers //////////////////
314   
315    ///////////////////////////////////////////////////////////
316    private ResourceREF getResourceREF(String resourceID) {
317        ResourceREF result = new ResourceREF();
318        result.setRef(resourceID);
319        return result;
320    }
321   
322 
323    //////////////////////////////////////////////////////
324    @Override
325    public int deleteAnnotationPrincipalPermissions(Number annotationID) throws SQLException {
326        StringBuilder sqlPermissions = new StringBuilder("DELETE FROM ");
327        sqlPermissions.append(permissionsTableName).append(" WHERE ").append(annotation_id).append(" = ?");
328        return getSimpleJdbcTemplate().update(sqlPermissions.toString(), annotationID); // removed "permission" rows
329       
330    }
331   
332     /////////////////////////////////////////////////////////////////////////////////////////
333    @Override
334    public int addAnnotationPrincipalPermission(Number annotationID, Number userID, Permission permission) throws SQLException {
335        Map<String, Object> paramsPermissions = new HashMap<String, Object>();
336        paramsPermissions.put("annotationId", annotationID);
337        paramsPermissions.put("principalId", userID);
338        paramsPermissions.put("status", permission.value());
339        StringBuilder sqlUpdatePermissionTable = new StringBuilder("INSERT INTO ");
340        sqlUpdatePermissionTable.append(permissionsTableName).append(" (").append(annotation_id).append(",").append(principal_id).append(",").append(this.permission ).append(") VALUES (:annotationId, :principalId, :status)");
341        final int affectedPermissions = getSimpleJdbcTemplate().update(sqlUpdatePermissionTable.toString(), paramsPermissions);
342        return affectedPermissions;
343    }
344   
345   
346      ///////////////////////////////////////////////////////////////////
347    @Override
348    public List<Map<Number, String>> retrievePermissions(Number annotationId) {
349        if (annotationId == null) {
350            return null;
351        }
352        StringBuilder sql = new StringBuilder("SELECT ");
353        sql.append(principal_id).append(",").append(permission).append(" FROM ").append(permissionsTableName).append(" WHERE ").append(annotation_id).append("  = ?");
354        return getSimpleJdbcTemplate().query(sql.toString(), principalsPermissionsRowMapper, annotationId.toString());
355    }
356    private final RowMapper<Map<Number, String>> principalsPermissionsRowMapper = new RowMapper<Map<Number, String>>() {
357        @Override
358        public Map<Number, String> mapRow(ResultSet rs, int rowNumber) throws SQLException {
359            Map<Number,String> result = new HashMap<Number, String>();
360            result.put(rs.getInt(principal_id),rs.getString(permission));
361            return result;
362        }
363    };
364   
365}
Note: See TracBrowser for help on using the repository browser.