Project

General

Profile

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

    
3
import eu.dnetlib.data.claims.migration.ClaimValidation;
4
import eu.dnetlib.data.claims.migration.ClaimValidationException;
5
import eu.dnetlib.data.claims.migration.entity.Claim;
6
import eu.dnetlib.data.claims.migration.entity.OpenaireEntity;
7
import eu.dnetlib.data.claims.migration.entity.Project;
8
import eu.dnetlib.data.claims.migration.entity.Result;
9
import eu.dnetlib.data.claimsDemo.ClaimUtils;
10
import eu.dnetlib.data.claimsDemo.QueryGenerator;
11
import eu.dnetlib.data.claimsDemo.SQLStoreException;
12
import eu.dnetlib.data.claimsDemo.SqlDAO;
13
import org.apache.log4j.Logger;
14

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

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

    
26
    SqlDAO sqlDAO = null;
27
    QueryGenerator queryGenerator = null;
28
    ResultHandler resultHandler = null;
29
    DMFContextHandler dmfContextHandler = null;
30
    ProjectHandler projectHandler = null;
31
    ClaimValidation claimValidation = null;
32
    Boolean useProductionIndex =  null;
33

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

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

    
53
       String query= null;
54
       /*if (claim.getSourceType().equals(ClaimUtils.CONTEXT)) {
55
           query = queryGenerator.generateInsertClaimContextQuery(resultHandler.generateSaveQueryForResult(((Result)claim.getTarget())),dmfContextHandler.generateSaveQueryForContext ((Context) claim.getSource()), claim);
56
       } else if (claim.getSourceType().equals(ClaimUtils.PROJECT)) {
57
           query = queryGenerator.generateInsertClaimProjectQuery(resultHandler.generateSaveQueryForResult((Result)claim.getTarget()), projectHandler.generateSaveQueryForProject((Project) claim.getSource()), claim);
58
       } else{
59
           query = queryGenerator.generateInsertClaimResultQuery(resultHandler.generateSaveQueryForResult((Result)claim.getTarget()), resultHandler.generateSaveQueryForResult((Result) claim.getSource()), claim);
60
       }*/
61
       query = queryGenerator.generateInsertFullClaimQuery(claim, params);
62
       return query;
63
   }
64
    /**
65
     * saves a claim in DB
66
     * @param claim
67
     * @throws Exception
68
     */
69
    //TODO make private - used in Migration
70
    public String saveClaim(Claim claim) throws SQLStoreException, SQLException {
71
        logger.info("Saving claim...");
72
        String id = null;
73
        ArrayList<Object> params = new ArrayList<>();
74
        String query = generateSaveQueryForClaim(claim, params);
75
        ResultSet rs=sqlDAO.executePreparedQuery(query, params);
76
        if(rs.next()) {
77
            id = rs.getString(1);
78
        }
79
        rs.close();
80
        return id;
81
    }
82
    // - used in Migration
83
    public void saveOrphanClaimId(String id) throws SQLStoreException, Exception {
84
        logger.info("Saving orphan claim id...");
85

    
86
        String query = queryGenerator.generateInsertQueryForClaimsOrphanIds(id);
87
        sqlDAO.executeUpdateQuery(query);
88
    }
89

    
90
    /**
91
     * Gets the main information for a claim relation - builds a claim object
92
     * exports metadata
93
     * and saves the claim relations in the DB
94
     * @param user
95
     * @param sourceType
96
     * @param sourceId
97
     * @param sourceCollectedFrom
98
     * @param targetType
99
     * @param targetId
100
     * @param targetCollectedFrom
101
     * @throws Exception
102
     */
103
    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) throws Exception, SQLStoreException {
104
        String id = null;
105

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

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

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

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

    
154
    }
155

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

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

    
174

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

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

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

    
211
                result.setAccessRights(accessRights);
212
                result.setEmbargoEndDate(embargoDate);
213
                return result;
214
            }else if (collectedFrom.equals(ClaimUtils.DATACITE)){
215
                Result result = externalRecordHandler.fetchResultfromDatacite(id);
216
                if(result == null){
217
                    logger.error("Record with id:"+id + " couldn't be fetched from datacite.");
218
                }else {
219
                    result.setAccessRights(accessRights);
220
                    result.setEmbargoEndDate(embargoDate);
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
                }
231
                return result;
232
            }else if (collectedFrom.equals(ClaimUtils.OPENAIRE)){
233
                IndexResultHandler indexResultHandler = new IndexResultHandler();
234
                Result result = null;
235
                if(type.equals(ClaimUtils.PUBLICATION)){
236
                    result = indexResultHandler.fetchPublicationById(id,useProductionIndex);
237

    
238
                }else if(type.equals(ClaimUtils.DATASET)){
239
                    result = indexResultHandler.fetchDatasetById(id,useProductionIndex);
240
                }else if(type.equals(ClaimUtils.SOFTWARE)){
241
                    result = indexResultHandler.fetchSoftwareById(id,useProductionIndex);
242
                }else if(type.equals(ClaimUtils.OTHER)){
243
                    result = indexResultHandler.fetchOtherById(id,useProductionIndex);
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 DMFContextHandler getDmfContextHandler() {
350
        return dmfContextHandler;
351
    }
352

    
353
    public void setDmfContextHandler(DMFContextHandler dmfContextHandler) {
354
        this.dmfContextHandler = dmfContextHandler;
355
    }
356

    
357
    public ProjectHandler getProjectHandler() {
358
        return projectHandler;
359
    }
360

    
361
    public void setProjectHandler(ProjectHandler projectHandler) {
362
        this.projectHandler = projectHandler;
363
    }
364

    
365
    public ClaimValidation getClaimValidation() {
366
        return claimValidation;
367
    }
368

    
369
    public void setClaimValidation(ClaimValidation claimValidation) {
370
        this.claimValidation = claimValidation;
371
    }
372

    
373
    public Boolean getUseProductionIndex() {
374
        return useProductionIndex;
375
    }
376

    
377
    public void setUseProductionIndex(Boolean useProductionIndex) {
378
        this.useProductionIndex = useProductionIndex;
379
    }
380
}
(1-1/12)