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

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

refactored DAO-s and creating an annotation in rest. Still 2 failures and 3 errors.

File size: 11.6 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.SourceDao;
22import eu.dasish.annotation.backend.dao.VersionDao;
23import eu.dasish.annotation.backend.identifiers.SourceIdentifier;
24import eu.dasish.annotation.backend.identifiers.VersionIdentifier;
25import eu.dasish.annotation.schema.NewOrExistingSourceInfo;
26import eu.dasish.annotation.schema.NewOrExistingSourceInfos;
27import eu.dasish.annotation.schema.NewSourceInfo;
28import eu.dasish.annotation.schema.Source;
29import eu.dasish.annotation.schema.SourceInfo;
30import java.sql.ResultSet;
31import java.sql.SQLException;
32import java.util.ArrayList;
33import java.util.HashMap;
34import java.util.List;
35import java.util.Map;
36import javax.sql.DataSource;
37import javax.xml.datatype.DatatypeConfigurationException;
38import javax.xml.datatype.XMLGregorianCalendar;
39import org.springframework.beans.factory.annotation.Autowired;
40import org.springframework.jdbc.core.RowMapper;
41
42/**
43 *
44 * @author olhsha
45 */
46public class JdbcSourceDao extends JdbcResourceDao implements SourceDao {
47
48    @Autowired
49    VersionDao versionDao;
50
51    public JdbcSourceDao(DataSource dataSource) {
52        setDataSource(dataSource);
53        internalIdName = source_id;
54        resourceTableName = sourceTableName;
55    }
56
57    //////////////////////////////////////////////////////////////////////////////////////////////////////
58    @Override
59    public SourceIdentifier getExternalID(Number internalID) {
60        return new SourceIdentifier(super.getExternalIdentifier(internalID));
61    }
62
63    ///////////////////////////////////////////////////////////////////////////////
64    @Override
65    public Source getSource(Number internalID) {
66        String sql = "SELECT " + sourceStar + "FROM " + sourceTableName + " WHERE " + source_id + " = ?";
67        List<Source> result = getSimpleJdbcTemplate().query(sql, sourceRowMapper, internalID);
68        return result.get(0);
69    }
70    private final RowMapper<Source> sourceRowMapper = new RowMapper<Source>() {
71        @Override
72        public Source mapRow(ResultSet rs, int rowNumber) throws SQLException {
73            try {
74                XMLGregorianCalendar xmlDate = Helpers.setXMLGregorianCalendar(rs.getTimestamp(time_stamp));
75                Source result = constructSource(new SourceIdentifier(rs.getString(external_id)), rs.getString(link_uri),
76                        versionDao.getExternalID(rs.getInt(version_id)), xmlDate);
77                return result;
78            } catch (DatatypeConfigurationException e) {
79                // TODO: which logger are we going to use?
80                System.out.println("Cannot construct time stamp: probably worng date/time format");
81                return null;
82            }
83        }
84    };
85
86   
87    ///////////////////////////////////////////////////////////////////
88    @Override
89    public int[] deleteSource(Number internalID) {
90
91        int[] result = new int[2];
92       
93        if (sourceIsInUse(internalID)){
94            result[0] =0;
95            result[1] =0;
96            return result;
97        }
98
99        List<Number> versions = retrieveVersionList(internalID);
100        String sqlSourcesVersions = "DELETE FROM " + sourcesVersionsTableName + " WHERE " + source_id + " = ?";
101        result[0] = getSimpleJdbcTemplate().update(sqlSourcesVersions, internalID);
102
103        String sql = "DELETE FROM " + sourceTableName + " WHERE " + source_id + " = ?";
104        result[1] = getSimpleJdbcTemplate().update(sql, internalID);
105
106        for (Number versionID : versions) {
107            versionDao.deleteVersion(versionID);
108        }
109
110        return result;
111
112    }
113
114    ///////////////////////////////////////////////////////////////////
115    @Override
116    public Number addSource(Source freshSource) throws SQLException {
117
118        SourceIdentifier externalIdentifier = new SourceIdentifier();
119        Number versionID = versionDao.getInternalID(new VersionIdentifier(freshSource.getVersion()));
120
121        if (versionID == null) {
122            System.out.println("Cannot add source because there is no version for it, and no cached representation. Create them and try again.");
123            return -1;
124        }
125
126        Map<String, Object> params = new HashMap<String, Object>();
127        params.put("externalId", externalIdentifier.toString());
128        params.put("linkUri", freshSource.getLink());
129        params.put("versionId", versionID);
130        String sql = "INSERT INTO " + sourceTableName + "(" + external_id + "," + link_uri + "," + version_id + " ) VALUES (:externalId, :linkUri,  :versionId)";
131        final int affectedRows = getSimpleJdbcTemplate().update(sql, params);
132
133
134        Map<String, Object> paramsJoint = new HashMap<String, Object>();
135        paramsJoint.put("sourceId", getInternalID(externalIdentifier));
136        paramsJoint.put("versionId", versionID);
137        String sqlJoint = "INSERT INTO " + sourcesVersionsTableName + "(" + source_id + "," + version_id + " ) VALUES (:sourceId, :versionId)";
138        final int affectedJointRows = getSimpleJdbcTemplate().update(sqlJoint, paramsJoint);
139
140
141        return (getInternalID(externalIdentifier));
142    }
143
144    /////////////////////////////////////////
145    @Override
146    public List<Number> retrieveVersionList(Number sourceID) {
147        String sql = "SELECT " + version_id + " FROM " + sourcesVersionsTableName + " WHERE " + source_id + " = ?";
148        List<Number> result = getSimpleJdbcTemplate().query(sql, versionsSourcesRunnerRowMapper, sourceID);
149        return result;
150    }
151    private final RowMapper<Number> versionsSourcesRunnerRowMapper = new RowMapper<Number>() {
152        @Override
153        public Number mapRow(ResultSet rs, int rowNumber) throws SQLException {
154            Number result = rs.getInt(version_id);
155            return result;
156        }
157    };
158
159    ///////////////////////////////////////////////////////////////////
160    @Override
161    public List<SourceInfo> getSourceInfos(List<Number> sources) {
162        if (sources == null) {
163            return null;
164        }
165        if (sources.isEmpty()) {
166            return new ArrayList<SourceInfo>();
167        }
168
169        String sourceIDs = makeListOfValues(sources);
170        String sql = "SELECT " + external_id + "," + link_uri + "," + version_id + " FROM " + sourceTableName + " WHERE " + source_id + " IN " + sourceIDs;
171        List<SourceInfo> result = getSimpleJdbcTemplate().query(sql, SourceInfoRowMapper);
172        return result;
173    }
174    private final RowMapper<SourceInfo> SourceInfoRowMapper = new RowMapper<SourceInfo>() {
175        @Override
176        public SourceInfo mapRow(ResultSet rs, int rowNumber) throws SQLException {
177            return constructSourceInfo(new SourceIdentifier(rs.getString(external_id)), rs.getString(link_uri), versionDao.getExternalID(rs.getInt(version_id)));
178        }
179    };
180
181 
182    /////////////////////////////////////////////////////
183    @Override
184    public List<Number> getSourcesForLink(String link) {
185        StringBuilder sql = new StringBuilder("SELECT ");
186        sql.append(source_id).append(" FROM ").append(sourceTableName).append(" WHERE ").append(link_uri).append(" LIKE '%").append(link).append("%'");
187        List<Number> result = getSimpleJdbcTemplate().query(sql.toString(), internalIDRowMapper);
188        return result;
189    }
190
191    ///////////////////////////////////////////////
192    @Override
193    public Map<String, String> addTargetSourcesToAnnotation(Number annotationID, List<NewOrExistingSourceInfo> sources) throws SQLException {
194        Map<String, String> result = new HashMap<String, String>();
195        for (NewOrExistingSourceInfo noesi : sources) {
196            SourceInfo source = noesi.getSource();
197            if (source != null) {
198                int affectedRows = addAnnotationSourcePair(annotationID, getInternalID(new SourceIdentifier(source.getRef())));
199            } else {
200                Number newSourceID = addNewSourceToAnnotation(annotationID, noesi.getNewSource());
201                if (newSourceID.intValue() == -1) {
202                    result.put(noesi.getNewSource().getId(), null);
203                } else {
204                    result.put(noesi.getNewSource().getId(), getExternalID(newSourceID).toString());
205                    int affectedRows = addAnnotationSourcePair(annotationID, newSourceID);
206                }
207            }
208        }
209        return result;
210    }
211
212    //////////// helpers ///////////////////////
213    /////////////////////////////////////////////////
214   
215      //////////////////////////////
216    private boolean sourceIsInUse(Number sourceID) {
217        String sql = "SELECT " + annotation_id + " FROM " + annotationsSourcesTableName + " WHERE " + source_id + "= ? LIMIT 1";
218        List<Number> result = getSimpleJdbcTemplate().query(sql, annotationIDRowMapper, sourceID);
219        if (result.size() > 0) {
220            return true;
221        }
222        return false;
223    }
224   
225      private final RowMapper<Number> annotationIDRowMapper = new RowMapper<Number>() {
226        @Override
227        public Number mapRow(ResultSet rs, int rowNumber) throws SQLException {
228            return rs.getInt(annotation_id);
229        }
230    };
231   
232    private int addAnnotationSourcePair(Number annotationID, Number sourceID) throws SQLException {
233        Map<String, Object> paramsAnnotationsSources = new HashMap<String, Object>();
234        paramsAnnotationsSources.put("annotationId", annotationID);
235        paramsAnnotationsSources.put("sourceId", sourceID);
236        String sqlAnnotationsSources = "INSERT INTO " + annotationsSourcesTableName + "(" + annotation_id + "," + source_id + " ) VALUES (:annotationId, :sourceId)";
237        int affectedRows = getSimpleJdbcTemplate().update(sqlAnnotationsSources, paramsAnnotationsSources);
238        return (affectedRows);
239    }
240    //////////////////////////////////////////////////////////////////////////////////
241
242    private Number addNewSourceToAnnotation(Number annotationID, NewSourceInfo source) throws SQLException {
243        Source newSource = new Source();
244        newSource.setLink(source.getLink());
245        newSource.setVersion(source.getVersion());
246        Number addedSourceID = addSource(newSource);// adding new source
247        if (addedSourceID.intValue() == -1) {
248            return -1;
249        }
250        int affectedRows = addAnnotationSourcePair(annotationID, addedSourceID);
251        return addedSourceID;
252    }
253
254    private SourceInfo constructSourceInfo(SourceIdentifier sourceIdentifier, String link, VersionIdentifier versionIdentifier) {
255        SourceInfo sourceInfo = new SourceInfo();
256        sourceInfo.setRef(sourceIdentifier.toString());
257        sourceInfo.setLink(link);
258        sourceInfo.setVersion(versionIdentifier.toString());
259        return sourceInfo;
260    }
261
262    private Source constructSource(SourceIdentifier sourceIdentifier, String link, VersionIdentifier version, XMLGregorianCalendar xmlTimeStamp) {
263        Source source = new Source();
264        source.setURI(sourceIdentifier.toString());
265        source.setTimeSatmp(xmlTimeStamp);
266        source.setLink(link);
267        source.setVersion(version.toString());
268
269        return source;
270    }
271}
Note: See TracBrowser for help on using the repository browser.