Project

General

Profile

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

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

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

    
32

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

    
36
    @Autowired
37
    private MonitorServiceImpl monitorApi;
38

    
39
    @Autowired
40
    private RepositoryService repositoryService;
41

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

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

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

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

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

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

    
62
    @Autowired
63
    private EmailUtils emailUtils;
64

    
65
    @Autowired
66
    private JobExecutor crisValidatorExecutor;
67

    
68
    @Autowired
69
    private MapJobDao crisJobs;
70

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

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

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

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

    
127
    }
128

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

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

    
166
        RuleSet ruleSet = null;
167
        for (List<RuleSet> ruleSets : this.rulesetMap.values()) {
168
            for (RuleSet rSet : ruleSets) {
169
                if (rSet.getName().equalsIgnoreCase("CRIS Validation")) {
170

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

    
193
    @Override
194
    public List<RuleSet> getRuleSets(String mode) {
195
        LOGGER.info("Getting rulesets for mode: " + mode);
196
        return rulesetMap.get(mode);
197
    }
198

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

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

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

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

    
264
            if (job.getDateFinished() != null) {
265
                sj.setEnded(job.getDateFinished().toString());
266
                sj.setDuration(Long.toString(job.getDateFinished().getTime() - job.getDateStarted().getTime()) + " seconds");
267
            } else {
268
                sj.setEnded("-");
269
                sj.setDuration("-");
270
            }
271
            sj.setStarted(job.getDateStarted().toString());
272

    
273
            sj.setUserEmail(job.getUser());
274
            sj.setCris(true);
275
            sj.setBaseUrl(job.getUrl());
276
            sj.setJobType("CRIS Validation");
277

    
278
            // TODO: status
279
            sj.setValidationStatus(job.getStatus());
280
            sj.setUsageJobStatus(job.getStatus());
281
            sj.setContentJobStatus(job.getStatus());
282

    
283
            // TODO: scores
284
//            sj.setFilteredScores();
285
            sj.setContentJobScore(job.getScore());
286
            sj.setUsageJobScore(job.getScore());
287

    
288
            jobs.add(sj);
289
        }
290
        /////////////////////////////////////////////////////////////////////////////////////////
291
        /////////////////////////////////////////////////////////////////////////////////////////
292
        return jobs;
293
    }
294

    
295
    @Override
296
    public int getStoredJobsTotalNumberNew(String user, String jobType, String validationStatus) throws  ValidatorServiceException {
297
        return getValidationService().getStoredJobsTotalNumberNew(user, jobType, validationStatus);
298
    }
299

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

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

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

    
322

    
323
}
(20-20/20)