Project

General

Profile

1
package eu.dnetlib.data.claims.handler;
2

    
3
import eu.dnetlib.data.claims.utils.ClaimValidation;
4
import eu.dnetlib.data.claims.utils.ClaimValidationException;
5
import eu.dnetlib.data.claims.entity.Claim;
6
import eu.dnetlib.data.claims.entity.OpenaireEntity;
7
import eu.dnetlib.data.claims.entity.Project;
8
import eu.dnetlib.data.claims.entity.Result;
9
import eu.dnetlib.data.claims.utils.ClaimUtils;
10
import eu.dnetlib.data.claims.utils.ContextUtils;
11
import eu.dnetlib.data.claims.utils.QueryGenerator;
12
import eu.dnetlib.data.claims.sql.SQLStoreException;
13
import eu.dnetlib.data.claims.sql.SqlDAO;
14
import org.apache.log4j.Logger;
15
import org.springframework.beans.factory.annotation.Autowired;
16

    
17
import java.sql.ResultSet;
18
import java.sql.SQLException;
19
import java.util.ArrayList;
20
import java.util.Date;
21
import java.util.List;
22

    
23
/**
24
 * Created by kiatrop on 5/2/2016.
25
 */
26
public class ClaimHandler {
27

    
28
    SqlDAO sqlDAO = null;
29
    QueryGenerator queryGenerator = null;
30
    ResultHandler resultHandler = null;
31
    ProjectHandler projectHandler = null;
32
    ClaimValidation claimValidation = null;
33
    @Autowired
34
    IndexResultHandler indexResultHandler;
35
    ContextUtils contextUtils;
36
    ExternalRecordHandler externalRecordHandler;
37

    
38
    private static final Logger logger = Logger.getLogger(ClaimHandler.class);
39

    
40
    /**
41
     * Saves a list of claims in DB
42
     * @param claims
43
     */
44
    public void saveClaims(List<Claim> claims){
45
        for(Claim claim:claims){
46
            try {
47
                saveClaim(claim);
48
            } catch (SQLStoreException e) {
49
                logger.error("Claim couldn't be saved : " + claim.getId() + "\n" + claim.toString(), e);
50
            } catch (SQLException e) {
51
                logger.error("Claim couldn't be saved : " + claim.getId() + "\n" + claim.toString(), e);
52
            }
53
        }
54
    }
55
   public String  generateSaveQueryForClaim(Claim claim, ArrayList<Object> params){
56

    
57
       String query= null;
58
       query = queryGenerator.generateInsertFullClaimQuery(claim, params);
59
       return query;
60
   }
61
    /**
62
     * saves a claim in DB
63
     * @param claim
64
     * @throws Exception
65
     */
66
    //TODO make private - used in Migration
67
    public String saveClaim(Claim claim) throws SQLStoreException, SQLException {
68
        logger.info("Saving claim...");
69
        String id = null;
70
        ArrayList<Object> params = new ArrayList<>();
71
        String query = generateSaveQueryForClaim(claim, params);
72
        ResultSet rs=sqlDAO.executePreparedQuery(query, params);
73
        if(rs.next()) {
74
            id = rs.getString(1);
75
        }
76
        rs.close();
77
        return id;
78
    }
79
    // - used in Migration
80
    public void saveOrphanClaimId(String id) throws SQLStoreException, Exception {
81
        logger.info("Saving orphan claim id...");
82

    
83
        String query = queryGenerator.generateInsertQueryForClaimsOrphanIds(id);
84
        sqlDAO.executeUpdateQuery(query);
85
    }
86

    
87
    /**
88
     * Gets the main information for a claim relation - builds a claim object
89
     * exports metadata
90
     * and saves the claim relations in the DB
91
     * @param user
92
     * @param sourceType
93
     * @param sourceId
94
     * @param sourceCollectedFrom
95
     * @param targetType
96
     * @param targetId
97
     * @param targetCollectedFrom
98
     * @throws Exception
99
     */
100
    public String buildAndInsertClaim(String user, String sourceType, String sourceId, String sourceCollectedFrom, String sourceAccessRights, String sourceEmbargoDate, String targetType, String targetId, String targetCollectedFrom, String targetAccessRights, String targetEmbargoDate, String claimedInDashboard ) throws Exception, SQLStoreException {
101
        String id = null;
102

    
103
        claimValidation.validateCollectedFrom(targetCollectedFrom);
104
        claimValidation.validateCollectedFrom(sourceCollectedFrom);
105
        logger.info("Trying to create a claim {user:"+user+", sourceType:"+sourceType+", sourceId:"+sourceId+", sourceCollectedFrom:"+sourceCollectedFrom+", sourceAccessRights:"+sourceAccessRights
106
                +", sourceEmbargoDate:"+sourceEmbargoDate +", targetType:"+targetType +", targetId:"+targetId +", targetCollectedFrom:"+targetCollectedFrom +", targetAccessRights:"+targetAccessRights
107
                +", targetEmbargoDate:"+targetEmbargoDate+"}");
108
        Claim claim = buildClaim(user,sourceType,sourceId,sourceCollectedFrom, sourceAccessRights, sourceEmbargoDate, targetType, targetId, targetCollectedFrom, targetAccessRights, targetEmbargoDate, claimedInDashboard);
109
        if(claimValidation.validateClaim(claim)) {
110
            claim = exportMedatataForClaim(claim);
111
            id = saveClaim(claim);
112
        }else{
113
            logger.info("claim is not valid");
114
        }
115
        return id;
116
    }
117

    
118
    /**
119
     * Gets the main information of a relation claim and
120
     * builds a claim object
121
     * @param user
122
     * @param sourceType publication, dataset, project, context
123
     * @param sourceId openaireId, doi or orcid workid
124
     * @param sourceCollectedFrom only for source with type publication, dataset
125
     * @param targetType publication, dataset, project, context
126
     * @param targetId openaireId, doi or orcid workid
127
     * @param targetCollectedFrom only for target with type publication, dataset
128
     * @return a claim object
129
     * @throws Exception
130
     */
131
    public Claim buildClaim(String user, String sourceType, String sourceId,String sourceCollectedFrom, String sourceAccessRights, String sourceEmbargoDate, String targetType,String targetId,String targetCollectedFrom, String targetAccessRights, String targetEmbargoDate, String claimedInDashboard ) throws Exception {
132
        Claim claim = new Claim();
133
        claim.setUserMail(user);
134
        claim.setClaimedInDashboard(claimedInDashboard);
135
        claim.setDate(new Date());
136
        //date
137
        claim.setSourceType(sourceType);
138
        claim.setTargetType(targetType);
139
        claim.setSource(buildOpenaireEntity(sourceId,sourceType,sourceCollectedFrom,sourceAccessRights, sourceEmbargoDate));
140
        claim.setTarget(buildOpenaireEntity(targetId,targetType,targetCollectedFrom, targetAccessRights, targetEmbargoDate));
141

    
142
        if (claim.getSource() == null) {
143
           throw new ClaimValidationException("The source id is invalid.");
144
        }
145

    
146
        if (claim.getTarget() == null) {
147
            throw new ClaimValidationException("The target id is invalid.");
148
        }
149
        //TODO from external sources need an OPenaireID
150
        return claim;
151

    
152
    }
153

    
154
    public boolean updateClaimCurationInfo(String curatedBy, String claimId, boolean approved) throws SQLStoreException, SQLException, Exception {
155
        logger.info("Updating claim curation info...");
156
        ArrayList<Object> params = new ArrayList<>();
157
        String query = queryGenerator.generateUpdateClaimCuration(curatedBy, claimId, approved, params);
158
        //ResultSet rs = sqlDAO.executeUpdateQuery(query, params);
159
        return sqlDAO.executeUpdateQuery(query, params);
160

    
161
        /*
162
        boolean success = false;
163
        while (rs.next())
164
        {
165
            success = true;
166
        }
167
        rs.close();
168
        return success;
169
        */
170
    }
171

    
172

    
173
    /**
174
     * Gets the main information of an openaire entityinfrastruct_::openaire
175
     * and returns a full  object
176
     * @param id
177
     * @param type
178
     * @param collectedFrom
179
     * @return openaire Entity (Context, Result, Project)
180
     * @throws Exception
181
     */
182
    public OpenaireEntity buildOpenaireEntity(String id, String type, String collectedFrom, String accessRights, String embargoDate) throws Exception {
183
        logger.debug(id+" "+ type+" "+collectedFrom);
184
        if(type==null){
185
            return null;
186
        }
187
        else if(type.equals(ClaimUtils.CONTEXT)){
188
            return contextUtils.fetchContextById(id);
189
        }else if (type.equals(ClaimUtils.PROJECT)){
190
            Project project = projectHandler.fetchProjectByID(id);
191
//            if(project == null){
192
//                project = projectHandler.fetchProjectByID(id);
193
//            }
194
            if(project == null){
195
                logger.error("Project with id:"+id + " couldn't be fetched.");
196
            }
197

    
198
            return project;
199
        }else if (type.equals(ClaimUtils.PUBLICATION)||type.equals(ClaimUtils.DATASET)||type.equals(ClaimUtils.SOFTWARE) ||type.equals(ClaimUtils.OTHER) ){
200
            if(collectedFrom == null){
201
                return null;
202
            }else if(collectedFrom.equals(ClaimUtils.CROSSREF)){
203

    
204
                Result result = externalRecordHandler.fetchResultfromCrossref(id);
205
                if(result == null){
206
                    logger.error("Record with id: " + id + " couldn't be fetched from crossref.");
207
                }
208

    
209
                result.setAccessRights(accessRights);
210
                result.setEmbargoEndDate(embargoDate);
211
                result.setResultType(type);
212
                return result;
213
            }else if (collectedFrom.equals(ClaimUtils.DATACITE)){
214
                Result result = externalRecordHandler.fetchResultfromDatacite(id);
215
                if(result == null){
216
                    logger.error("Record with id:"+id + " couldn't be fetched from datacite.");
217
                }else {
218
                    result.setAccessRights(accessRights);
219
                    result.setEmbargoEndDate(embargoDate);
220
                    result.setResultType(type);
221
                }
222
                return result;
223
            }else if (collectedFrom.equals(ClaimUtils.ORCID)){
224
                Result result = externalRecordHandler.fetchResultfromOrcid(id);
225
                if(result == null){
226
                    logger.error("Record with id:"+id + " couldn't be fetched from ORCID.");
227
                }else {
228
                    result.setAccessRights(accessRights);
229
                    result.setEmbargoEndDate(embargoDate);
230
                    result.setResultType(type);
231
                }
232
                return result;
233
            }else if (collectedFrom.equals(ClaimUtils.OPENAIRE)){
234
                Result result = null;
235
                if(type.equals(ClaimUtils.PUBLICATION)){
236
                    result = indexResultHandler.fetchPublicationById(id);
237

    
238
                }else if(type.equals(ClaimUtils.DATASET)){
239
                    result = indexResultHandler.fetchDatasetById(id);
240
                }else if(type.equals(ClaimUtils.SOFTWARE)){
241
                    result = indexResultHandler.fetchSoftwareById(id);
242
                }else if(type.equals(ClaimUtils.OTHER)){
243
                    result = indexResultHandler.fetchOtherById(id);
244
                }
245
                if(result == null){
246
                    logger.error("Record with id:"+id + " and type " + type + " couldn't be fetched from openaire.");
247
                }
248
                return result;
249
            }
250
        }
251
        return null;
252
    }
253

    
254

    
255
    /**
256
     * Exports the metadata for the source and the target of a claim and sets the proper field
257
     * @param claim
258
     * @return claim with the proper metadata path of the result of source and target
259
     */
260
    public Claim exportMedatataForClaim(Claim claim){
261
        if(claim.getTargetType().equals(ClaimUtils.DATASET)||claim.getTargetType().equals(ClaimUtils.PUBLICATION)){
262
            String path = resultHandler.exportMetadataFileForResult((Result)claim.getTarget());
263
            ((Result) claim.getTarget()).setRecordPath(path);
264
        }
265
        if(claim.getSourceType().equals(ClaimUtils.DATASET)||claim.getSourceType().equals(ClaimUtils.PUBLICATION)){
266
            String path = resultHandler.exportMetadataFileForResult((Result)claim.getSource());
267
            ((Result) claim.getSource()).setRecordPath(path);
268
        }
269
        return claim;
270

    
271
    }
272

    
273
    public void deleteClaim(String user, String claimId) throws SQLStoreException, Exception {
274

    
275
        ArrayList<Object> params = new ArrayList<>();
276
        String query = queryGenerator.generateSelectClaimQuery(claimId,user, params);
277
        ResultSet rs = sqlDAO.executePreparedQuery(query, params);
278
        if(rs.next()) {
279
            String sourceType =rs.getString(2);
280
            String sourceId =rs.getString(3);
281
            String targetType =rs.getString(4);
282
            String targetId =rs.getString(5);
283
            this.checkRecordFile(sourceType, sourceId);
284
            this.checkRecordFile(targetType, targetId);
285

    
286
            ArrayList<Object> params2 = new ArrayList<>();
287
            String query2 = queryGenerator.generateDeleteFullClaimQuery(claimId,user,sourceType,sourceId,targetType,targetId, params2);
288
            sqlDAO.executeUpdateQuery(query2, params2);
289
        }else{
290
            logger.error("Claim with id : "+ claimId+" user:  "+user+" couldn't be deleted." );
291
        }
292
        rs.close();
293
    }
294

    
295
    public void checkRecordFile(String type, String id) throws SQLStoreException, SQLException {
296
        if(type.equals("publication") || type.equals("dataset")|| type.equals("other")|| type.equals("software")){
297
            this.resultHandler.deleteRecordFile(type,id);
298
        }
299
    }
300
    public boolean deleteClaim(String claimId) throws Exception, SQLStoreException {
301

    
302
        ArrayList<Object> params = new ArrayList<>();
303
        String query = queryGenerator.generateSelectClaimQuery(claimId, params);
304
        ResultSet rs = sqlDAO.executePreparedQuery(query, params);
305
        if(rs.next()) {
306
            String sourceType =rs.getString(2);
307
            String sourceId =rs.getString(3);
308
            String targetType =rs.getString(4);
309
            String targetId =rs.getString(5);
310
            String user =rs.getString(6);
311
            this.checkRecordFile(sourceType, sourceId);
312
            this.checkRecordFile(targetType, targetId);
313
            ArrayList<Object> params2 = new ArrayList<>();
314
            String query2 = queryGenerator.generateDeleteFullClaimQuery(claimId,user,sourceType,sourceId,targetType,targetId, params2);
315
            sqlDAO.executeUpdateQuery(query2, params2);
316
            rs.close();
317
            return  true;
318
        }
319
        rs.close();
320
        logger.error("Couldn't delete claim with id : " + claimId +". It doesn't not exist.");
321
        return false;
322

    
323
    }
324

    
325
    public SqlDAO getSqlDAO() {
326
        return sqlDAO;
327
    }
328

    
329
    public void setSqlDAO(SqlDAO sqlDAO) {
330
        this.sqlDAO = sqlDAO;
331
    }
332

    
333
    public QueryGenerator getQueryGenerator() {
334
        return queryGenerator;
335
    }
336

    
337
    public void setQueryGenerator(QueryGenerator queryGenerator) {
338
        this.queryGenerator = queryGenerator;
339
    }
340

    
341
    public ResultHandler getResultHandler() {
342
        return resultHandler;
343
    }
344

    
345
    public void setResultHandler(ResultHandler resultHandler) {
346
        this.resultHandler = resultHandler;
347
    }
348

    
349
    public ProjectHandler getProjectHandler() {
350
        return projectHandler;
351
    }
352

    
353
    public void setProjectHandler(ProjectHandler projectHandler) {
354
        this.projectHandler = projectHandler;
355
    }
356

    
357
    public ClaimValidation getClaimValidation() {
358
        return claimValidation;
359
    }
360

    
361
    public void setClaimValidation(ClaimValidation claimValidation) {
362
        this.claimValidation = claimValidation;
363
    }
364

    
365
    public ContextUtils getContextUtils() {
366
        return contextUtils;
367
    }
368

    
369
    public void setContextUtils(ContextUtils contextUtils) {
370
        this.contextUtils = contextUtils;
371
    }
372

    
373
    public IndexResultHandler getIndexResultHandler() {
374
        return indexResultHandler;
375
    }
376

    
377
    public void setIndexResultHandler(IndexResultHandler indexResultHandler) {
378
        this.indexResultHandler = indexResultHandler;
379
    }
380

    
381
    public ExternalRecordHandler getExternalRecordHandler() {
382
        return externalRecordHandler;
383
    }
384

    
385
    public void setExternalRecordHandler(ExternalRecordHandler externalRecordHandler) {
386
        this.externalRecordHandler = externalRecordHandler;
387
    }
388
}
(1-1/12)