Project

General

Profile

1
package eu.dnetlib.repo.manager.service;
2

    
3
import eu.dnetlib.api.functionality.ValidatorServiceException;
4
import eu.dnetlib.domain.data.Repository;
5
import eu.dnetlib.domain.data.RepositoryInterface;
6
import eu.dnetlib.domain.functionality.validator.*;
7
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
8
import eu.dnetlib.repo.manager.shared.Constants;
9
import eu.dnetlib.repo.manager.shared.InterfaceInformation;
10
import eu.dnetlib.repo.manager.shared.ValidationServiceException;
11
import eu.dnetlib.repo.manager.utils.OaiTools;
12
import gr.uoa.di.driver.util.ServiceLocator;
13
import org.apache.log4j.Logger;
14
import org.eurocris.openaire.cris.validator.model.Job;
15
import org.eurocris.openaire.cris.validator.service.JobExecutor;
16
import org.eurocris.openaire.cris.validator.service.MapJobDao;
17
import org.json.JSONException;
18
import org.springframework.beans.factory.annotation.Autowired;
19
import org.springframework.http.HttpStatus;
20
import org.springframework.http.ResponseEntity;
21
import org.springframework.security.access.prepost.PreAuthorize;
22
import org.springframework.security.core.context.SecurityContextHolder;
23
import org.springframework.stereotype.Service;
24

    
25
import javax.annotation.PostConstruct;
26
import javax.annotation.Resource;
27
import java.util.*;
28
import java.util.concurrent.ConcurrentHashMap;
29
import java.util.stream.Collectors;
30

    
31

    
32
@Service("validatorService")
33
public class ValidatorServiceImpl implements ValidatorService {
34

    
35
    @Autowired
36
    private MonitorServiceImpl monitorApi;
37

    
38
    @Autowired
39
    private RepositoryService repositoryService;
40

    
41
    @Resource(name = "validatorServiceLocator")
42
    private ServiceLocator<eu.dnetlib.api.functionality.ValidatorService> validatorServiceLocator;
43

    
44
    private eu.dnetlib.api.functionality.ValidatorService getValidationService() {
45
        return this.validatorServiceLocator.getService();
46
    }
47

    
48
    public ServiceLocator<eu.dnetlib.api.functionality.ValidatorService> getValidatorServiceLocator() {
49
        return validatorServiceLocator;
50
    }
51

    
52
    public void setValidatorServiceLocator(ServiceLocator<eu.dnetlib.api.functionality.ValidatorService> validatorServiceLocator) {
53
        this.validatorServiceLocator = validatorServiceLocator;
54
    }
55

    
56
    private Map<String, List<RuleSet>> rulesetMap = new ConcurrentHashMap<String, List<RuleSet>>();
57

    
58
    private static final Logger LOGGER = Logger
59
            .getLogger(ValidatorServiceImpl.class);
60

    
61
    @Autowired
62
    private EmailUtils emailUtils;
63

    
64
    @Autowired
65
    private JobExecutor crisValidatorExecutor;
66

    
67
    @Autowired
68
    private MapJobDao crisJobs;
69

    
70
    @PostConstruct
71
    private void loadRules(){
72
        LOGGER.debug("PostConstruct method! Load rules!");
73
        try {
74
            for (RuleSet ruleSet : getValidationService().getRuleSets()) {
75
                if (ruleSet.getVisibility() != null && ruleSet.getVisibility().contains("development")) {
76
                    String key = "";
77
                    if (ruleSet.getGuidelinesAcronym().matches("^openaire[1-9].0_data$"))
78
                        key = Constants.VALIDATION_MODE_DATA;
79
                    else if (ruleSet.getGuidelinesAcronym().matches("^openaire[1-9].0$") || ruleSet.getGuidelinesAcronym().equals("driver"))
80
                        key = Constants.VALIDATION_MODE_LITERATURE;
81
                    else if (ruleSet.getGuidelinesAcronym().matches("^openaire[1-9].0_cris$"))
82
                        key = Constants.VALIDATION_MODE_CRIS;
83

    
84
                    if (rulesetMap.containsKey(key))
85
                        rulesetMap.get(key).add(ruleSet);
86
                    else {
87
                        List<RuleSet> ruleSets = new ArrayList<RuleSet>();
88
                        ruleSets.add(ruleSet);
89
                        rulesetMap.put(key, ruleSets);
90
                    }
91
                }
92
            }
93

    
94
            /////////////////////////////////////////////////////////////////////////////////////////
95
            // FIXME: this is a hack for CRIS Jan Dvorak Validator, should be implemented properly //
96
            /////////////////////////////////////////////////////////////////////////////////////////
97
            int ruleId = -1000;
98
            Rule rule = new Rule();
99
            rule.setType("cris");
100
            rule.setName("CRIS Rules");
101
            rule.setId(ruleId);
102
            rule.setMandatory(true);
103
            RuleSet crisRuleSet = new RuleSet();
104
            crisRuleSet.setContentRulesIds(Collections.singleton(ruleId));
105
            crisRuleSet.setContentRules(Collections.singletonList(rule));
106
            crisRuleSet.setUsageRulesIds(Collections.singleton(ruleId));
107
            crisRuleSet.setUsageRules(Collections.singletonList(rule));
108
            crisRuleSet.setId(-1);
109
            crisRuleSet.setDescription("Validates using the CRIS Validator implementation");
110
            crisRuleSet.setName("CRIS Validation");
111

    
112
            String crisKey = Constants.VALIDATION_MODE_CRIS;
113
            if (rulesetMap.containsKey(crisKey))
114
                rulesetMap.get(crisKey).add(crisRuleSet);
115
            else {
116
                List<RuleSet> ruleSets = new ArrayList<RuleSet>();
117
                ruleSets.add(crisRuleSet);
118
                rulesetMap.put(crisKey, ruleSets);
119
            }
120
            /////////////////////////////////////////////////////////////////////////////////////////
121
            /////////////////////////////////////////////////////////////////////////////////////////
122
        } catch (ValidatorServiceException e) {
123
            LOGGER.error(e);
124
        }
125

    
126
    }
127

    
128
    @Override
129
    @PreAuthorize("hasRole('ROLE_USER') and #jobForValidation.userEmail == authentication.userInfo.email")
130
    public JobForValidation submitJobForValidation(JobForValidation jobForValidation) throws ValidatorServiceException {
131
        LOGGER.debug("Submit job for validation with id : " + jobForValidation.getDatasourceId());
132
        try {
133
            emailUtils.sendSubmitJobForValidationEmail(SecurityContextHolder.getContext().getAuthentication(),jobForValidation);
134
            /////////////////////////////////////////////////////////////////////////////////////////
135
            // FIXME: this is a hack for CRIS Jan Dvorak Validator, should be implemented properly //
136
            /////////////////////////////////////////////////////////////////////////////////////////
137
            if (jobForValidation.getSelectedContentRules().size() == 1 &&
138
                    jobForValidation.getSelectedContentRules().contains(-1000)) {
139
                crisValidatorExecutor.submit(jobForValidation.getBaseUrl(), jobForValidation.getUserEmail());
140
            } else {
141
                this.getValidationService().submitValidationJob(jobForValidation);
142
            }
143
            /////////////////////////////////////////////////////////////////////////////////////////
144
            /////////////////////////////////////////////////////////////////////////////////////////
145
//            this.getValidationService().submitValidationJob(jobForValidation);
146
        } catch (ValidatorServiceException e) {
147
            LOGGER.debug("Exception on submitJobForValidation" , e);
148
            emailUtils.reportException(e);
149
            throw e;
150
        } catch (Exception e) {
151
            LOGGER.error(e);
152
        }
153
        return jobForValidation;
154
    }
155

    
156
    @Override
157
    @PreAuthorize("hasRole('ROLE_USER') and #email == authentication.userInfo.email")
158
    public ResponseEntity<Object> reSubmitJobForValidation(String email,
159
                                                           String jobId) throws JSONException, ValidatorServiceException {
160
        LOGGER.debug("Resubmit validation job with id : " + jobId);
161
        StoredJob job = monitorApi.getJobSummary(jobId, "all");
162
        Set<Integer> contentRules = new HashSet<Integer>();
163
        Set<Integer> usageRules = new HashSet<Integer>();
164

    
165
        RuleSet ruleSet = null;
166
        for (List<RuleSet> ruleSets : this.rulesetMap.values()) {
167
            for (RuleSet rSet : ruleSets)
168
                if (rSet.getGuidelinesAcronym().equals(job.getDesiredCompatibilityLevel())) {
169
                    ruleSet = rSet;
170
                    break;
171
                }
172
        }
173
        if (ruleSet != null){
174
            for (int ruleId : job.getRules()) {
175
                if (ruleSet.getContentRulesIds().contains(ruleId))
176
                    contentRules.add(ruleId);
177
                else if (ruleSet.getUsageRulesIds().contains(ruleId))
178
                    usageRules.add(ruleId);
179
            }
180
        }
181
        if (!contentRules.isEmpty())
182
            job.setSelectedContentRules(contentRules);
183
        if (!usageRules.isEmpty())
184
            job.setSelectedUsageRules(usageRules);
185
        this.submitJobForValidation(job);
186
        return new ResponseEntity<>("OK",HttpStatus.OK);
187
    }
188

    
189
    @Override
190
    public List<RuleSet> getRuleSets(String mode) {
191
        LOGGER.info("Getting rulesets for mode: " + mode);
192
        return rulesetMap.get(mode);
193
    }
194

    
195
    @Override
196
    public List<String> getSetsOfRepository(String url) {
197
        LOGGER.debug("Getting sets of repository with url : " + url);
198
        try {
199
            return OaiTools.getSetsOfRepo(url);
200
        } catch (Exception e) {
201
            LOGGER.debug("Exception on getSetsOfRepository" , e);
202
            emailUtils.reportException(e);
203
        }
204
        return null;
205
    }
206

    
207
    @Override
208
    public boolean identifyRepo(String url) {
209
        LOGGER.debug("Identify repository with url : " + url);
210
        try {
211
            return OaiTools.identifyRepository(url);
212
        } catch (Exception e) {
213
            LOGGER.error("Error while identifying repository with url: " + url, e);
214
            emailUtils.reportException(e);
215
            return false;
216
        }
217
    }
218

    
219
    @Override
220
    public RuleSet getRuleSet(String acronym) {
221
        LOGGER.debug("Getting ruleset with acronym : " + acronym);
222
        RuleSet ruleSet = null;
223
        try {
224
            for (List<RuleSet> ruleSets : this.rulesetMap.values()) {
225
                for (RuleSet rSet : ruleSets)
226
                    if (rSet.getGuidelinesAcronym().equals(acronym)) {
227
                        ruleSet = rSet;
228
                        break;
229
                    }
230
            }
231
            return ruleSet;
232
        } catch (Exception e) {
233
            LOGGER.error("Error getting ruleset", e);
234
            emailUtils.reportException(e);
235
            return null;
236
        }
237
    }
238

    
239
    @Override
240
    @PreAuthorize("hasRole('ROLE_USER')")
241
    public List<StoredJob> getStoredJobsNew(String user,
242
                                            String jobType,
243
                                            String offset,
244
                                            String limit,
245
                                            String dateFrom,
246
                                            String dateTo,
247
                                            String validationStatus ) throws ValidatorServiceException {
248
//        return getValidationService().getStoredJobsNew(user, jobType, Integer.parseInt(offset), Integer.parseInt(limit), dateFrom, dateTo, validationStatus);
249
        List<StoredJob> jobs = getValidationService().getStoredJobsNew(user, jobType, Integer.parseInt(offset), Integer.parseInt(limit), dateFrom, dateTo, validationStatus);
250
        /////////////////////////////////////////////////////////////////////////////////////////
251
        // FIXME: this is a hack for CRIS Jan Dvorak Validator, should be implemented properly //
252
        /////////////////////////////////////////////////////////////////////////////////////////
253
        if (jobs == null) {
254
            jobs = new ArrayList<>();
255
        }
256
        List<Job> cj = crisJobs.getJobs(user);
257
        for (Job job : cj) {
258
            StoredJob sj = new StoredJob();
259

    
260
            if (job.getDateFinished() != null) {
261
                sj.setEnded(job.getDateFinished().toString());
262
                sj.setDuration(Long.toString(job.getDateFinished().getTime() - job.getDateStarted().getTime()) + " seconds");
263
            } else {
264
                sj.setEnded("-");
265
                sj.setDuration("-");
266
            }
267
            sj.setStarted(job.getDateStarted().toString());
268

    
269
            sj.setUserEmail(job.getUser());
270
            sj.setCris(true);
271
            sj.setBaseUrl(job.getUrl());
272
            sj.setJobType("CRIS Validation");
273

    
274
            // TODO: status
275
            sj.setValidationStatus(job.getStatus());
276
            sj.setUsageJobStatus(job.getStatus());
277
            sj.setContentJobStatus(job.getStatus());
278

    
279
            // TODO: scores
280
//            sj.setFilteredScores();
281
            sj.setContentJobScore(job.getScore());
282
            sj.setUsageJobScore(job.getScore());
283

    
284
            jobs.add(sj);
285
        }
286
        /////////////////////////////////////////////////////////////////////////////////////////
287
        /////////////////////////////////////////////////////////////////////////////////////////
288
        return jobs;
289
    }
290

    
291
    @Override
292
    public int getStoredJobsTotalNumberNew(String user, String jobType, String validationStatus) throws  ValidatorServiceException {
293
        return getValidationService().getStoredJobsTotalNumberNew(user, jobType, validationStatus);
294
    }
295

    
296
    @Override
297
    public InterfaceInformation getInterfaceInformation(String baseUrl) throws ValidationServiceException {
298
        try {
299
            LOGGER.debug("Getting interface information with url: " + baseUrl);
300
            InterfaceInformation interfaceInformation = new InterfaceInformation();
301
            interfaceInformation.setIdentified(this.identifyRepo(baseUrl));
302
            if (interfaceInformation.isIdentified())
303
                interfaceInformation.setSets(this.getSetsOfRepository(baseUrl));
304

    
305
            return interfaceInformation;
306
        } catch (Exception e) {
307
            LOGGER.error("Error getting interface information with url: " + baseUrl, e);
308
            emailUtils.reportException(e);
309
            throw new ValidationServiceException("login.generalError", ValidationServiceException.ErrorCode.GENERAL_ERROR);
310
        }
311
    }
312

    
313
    @Override
314
    public List<StoredJob> getJobsSummary(String repoId, int limit) throws JSONException, ValidatorServiceException {
315
        return getValidationService().getJobSummary(repositoryService.getRepositoryInterface(repoId).stream().map(RepositoryInterface::getBaseUrl).collect(Collectors.toList()),limit);
316
    }
317

    
318

    
319
}
(20-20/20)