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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
319

    
320
}
(20-20/20)