Project

General

Profile

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

    
3
import eu.dnetlib.data.claims.entity.Claim;
4
import eu.dnetlib.data.claims.entity.OpenaireEntity;
5
import eu.dnetlib.data.claims.entity.Project;
6
import eu.dnetlib.data.claims.entity.Result;
7
import eu.dnetlib.data.claims.sql.SQLStoreException;
8
import eu.dnetlib.data.claims.sql.SqlDAO;
9
import eu.dnetlib.data.claims.utils.*;
10
import org.apache.logging.log4j.LogManager;
11
import org.apache.logging.log4j.Logger;
12
import org.springframework.beans.factory.annotation.Autowired;
13

    
14
import java.sql.ResultSet;
15
import java.sql.SQLException;
16
import java.util.ArrayList;
17
import java.util.Date;
18
import java.util.List;
19

    
20
/**
21
 * Created by kiatrop on 5/2/2016.
22
 */
23
public class ClaimHandler {
24

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

    
35
    private static final Logger logger = LogManager.getLogger(ClaimHandler.class);
36

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

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

    
80
        String query = queryGenerator.generateInsertQueryForClaimsOrphanIds(id);
81
        sqlDAO.executeUpdateQuery(query);
82
    }
83

    
84
    /**
85
     * Gets the main information for a claim relation - builds a claim object
86
     * exports metadata
87
     * and saves the claim relations in the DB
88
     * @param user
89
     * @param sourceType
90
     * @param sourceId
91
     * @param sourceCollectedFrom
92
     * @param targetType
93
     * @param targetId
94
     * @param targetCollectedFrom
95
     * @throws Exception
96
     */
97
    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 {
98
        String id = null;
99

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

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

    
139
        if (claim.getSource() == null) {
140
           throw new ClaimValidationException("The source id is invalid.");
141
        }
142

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

    
149
    }
150

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

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

    
169

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

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

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

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

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

    
251

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

    
268
    }
269

    
270
    public void deleteClaim(String user, String claimId) throws SQLStoreException, Exception {
271

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

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

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

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

    
320
    }
321

    
322
    public SqlDAO getSqlDAO() {
323
        return sqlDAO;
324
    }
325

    
326
    public void setSqlDAO(SqlDAO sqlDAO) {
327
        this.sqlDAO = sqlDAO;
328
    }
329

    
330
    public QueryGenerator getQueryGenerator() {
331
        return queryGenerator;
332
    }
333

    
334
    public void setQueryGenerator(QueryGenerator queryGenerator) {
335
        this.queryGenerator = queryGenerator;
336
    }
337

    
338
    public ResultHandler getResultHandler() {
339
        return resultHandler;
340
    }
341

    
342
    public void setResultHandler(ResultHandler resultHandler) {
343
        this.resultHandler = resultHandler;
344
    }
345

    
346
    public ProjectHandler getProjectHandler() {
347
        return projectHandler;
348
    }
349

    
350
    public void setProjectHandler(ProjectHandler projectHandler) {
351
        this.projectHandler = projectHandler;
352
    }
353

    
354
    public ClaimValidation getClaimValidation() {
355
        return claimValidation;
356
    }
357

    
358
    public void setClaimValidation(ClaimValidation claimValidation) {
359
        this.claimValidation = claimValidation;
360
    }
361

    
362
    public ContextUtils getContextUtils() {
363
        return contextUtils;
364
    }
365

    
366
    public void setContextUtils(ContextUtils contextUtils) {
367
        this.contextUtils = contextUtils;
368
    }
369

    
370
    public IndexResultHandler getIndexResultHandler() {
371
        return indexResultHandler;
372
    }
373

    
374
    public void setIndexResultHandler(IndexResultHandler indexResultHandler) {
375
        this.indexResultHandler = indexResultHandler;
376
    }
377

    
378
    public ExternalRecordHandler getExternalRecordHandler() {
379
        return externalRecordHandler;
380
    }
381

    
382
    public void setExternalRecordHandler(ExternalRecordHandler externalRecordHandler) {
383
        this.externalRecordHandler = externalRecordHandler;
384
    }
385
}
(1-1/13)