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

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

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

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

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

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

    
147
    }
148

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

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

    
167

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

    
193
            return project;
194
        }else if (type.equals(ClaimUtils.PUBLICATION)||type.equals(ClaimUtils.DATASET)||type.equals(ClaimUtils.SOFTWARE) ){
195
            ExternalRecordHandler externalRecordHandler = new ExternalRecordHandler();
196
            if(collectedFrom == null){
197
                return null;
198
            }else if(collectedFrom.equals(ClaimUtils.CROSSREF)){
199

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

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

    
232
                }else if(type.equals(ClaimUtils.DATASET)){
233
                    result = indexResultHandler.fetchDatasetById(id,useProductionIndex);
234
                }else if(type.equals(ClaimUtils.SOFTWARE)){
235
                    result = indexResultHandler.fetchSoftwareById(id,useProductionIndex);
236
                }
237
                if(result == null){
238
                    logger.error("Record with id:"+id + " and type " + type + " couldn't be fetched from openaire.");
239
                }
240
                return result;
241
            }
242
        }
243
        return null;
244
    }
245

    
246

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

    
263
    }
264

    
265
    public void deleteClaim(String user, String claimId) throws SQLStoreException, Exception {
266

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

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

    
287
    public void checkRecordFile(String type, String id) throws SQLStoreException, SQLException {
288
        if(type.equals("publication") || type.equals("dataset")){
289
            this.resultHandler.deleteRecordFile(type,id);
290
        }
291
    }
292
    public boolean deleteClaim(String claimId) throws Exception, SQLStoreException {
293

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

    
313
    }
314

    
315
    public SqlDAO getSqlDAO() {
316
        return sqlDAO;
317
    }
318

    
319
    public void setSqlDAO(SqlDAO sqlDAO) {
320
        this.sqlDAO = sqlDAO;
321
    }
322

    
323
    public QueryGenerator getQueryGenerator() {
324
        return queryGenerator;
325
    }
326

    
327
    public void setQueryGenerator(QueryGenerator queryGenerator) {
328
        this.queryGenerator = queryGenerator;
329
    }
330

    
331
    public ResultHandler getResultHandler() {
332
        return resultHandler;
333
    }
334

    
335
    public void setResultHandler(ResultHandler resultHandler) {
336
        this.resultHandler = resultHandler;
337
    }
338

    
339
    public DMFContextHandler getDmfContextHandler() {
340
        return dmfContextHandler;
341
    }
342

    
343
    public void setDmfContextHandler(DMFContextHandler dmfContextHandler) {
344
        this.dmfContextHandler = dmfContextHandler;
345
    }
346

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

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

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

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

    
363
    public Boolean getUseProductionIndex() {
364
        return useProductionIndex;
365
    }
366

    
367
    public void setUseProductionIndex(Boolean useProductionIndex) {
368
        this.useProductionIndex = useProductionIndex;
369
    }
370
}
(1-1/12)