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 =  false;
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
        logger.info("HEEEEREEE");
186
        if(type==null){
187
            return null;
188
        }
189
        else if(type.equals(ClaimUtils.CONTEXT)){
190
            return DMFContextHandler.fetchContextById(id);
191
        }else if (type.equals(ClaimUtils.PROJECT)){
192
            Project project = projectHandler.fetchProjectByID(id, false);
193
            if(project == null){
194
                project = projectHandler.fetchProjectByID(id, true);
195
            }
196
            if(project == null){
197
                logger.error("Project with id:"+id + " couldn't be fetched.");
198
            }
199

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

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

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

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

    
255

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

    
272
    }
273

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

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

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

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

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

    
322
    }
323

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

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

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

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

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

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

    
348
    public DMFContextHandler getDmfContextHandler() {
349
        return dmfContextHandler;
350
    }
351

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

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

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

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

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

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

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